使用jQuery查找并替换HTML字符串
数据库中的链接是网站标题,并在页面上呈现有趣的文章:作者 - 但偶尔会链接是一个问题哪里是中国?:GoogleMaps。 ?:
看起来很傻,所以我想用?< / span>: c>?< / span> 。
Links from the database are website titles and render on the page "Interesting Article: Author" - but occasionally the link is a question "Where's China?: GoogleMaps". The ?:
looks silly so I wanted to replace the HTML ?</span>:
with ?</span>
.
这是我制定的jQuery:
Here is the jQuery I worked out:
$('#relatedinfo ul li a')。html()。replace('?< / span>:','?< / span>');
但实际上并没有在DOM中取代它。如何让该字符串实际更改页面?
But this doesn't actually replace it in the DOM. How do I get that string to actually change the page?
我建议:
$('#relatedinfo ul li a').html(function(index,html){
return html.replace(/<\/span>(\:)/,'');
});
甚至:
$('#relatedinfo ul li a').text(function(index,text){
return text.replace(':','');
});
更新的方法是检查 span $中的最后一个字符c $ c>在
['?','!','。']
的数组中,如果是,则删除:
来自nextSibling的nodeValue:
An updated approach is to check that the last character in the span
is in the array of ['?','!','.']
and, if it is, then to remove the :
from the nextSibling's nodeValue:
$('#relatedinfo ul li a span').text(function(index,text){
var lastchar = text.split('').pop();
if (['?','!','.'].indexOf(lastchar) > -1) {
this.nextSibling.nodeValue = this.nextSibling.nodeValue.replace(':','');
}
});
参考文献:
-
html()
。 -
String .replace()
。 -
text()
。
-
html()
. -
String.replace()
. -
text()
.