本文介绍了使用jQuery查找并替换HTML字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

限时删除!!

数据库中的链接是网站标题,并在页面上呈现:作者 - 但偶尔会链接是一个问题:GoogleMaps。 ?:看起来很傻,所以我想用<$ c $替换HTML ?< / 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 ['?','!','。'] 的数组中,如果是,则删除来自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().

这篇关于使用jQuery查找并替换HTML字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

1403页,肝出来的..

09-06 07:05