【问题标题】:Find and replace HTML string with jQuery用 jQuery 查找和替换 HTML 字符串
【发布时间】:2013-02-18 15:53:44
【问题描述】:

来自数据库的链接是网站标题并呈现在“Interesting Article: Author”页面上 - 但有时链接是一个问题“Where's China?: GoogleMaps”。 ?: 看起来很傻,所以我想用 ?</span> 替换 HTML ?</span>:

这是我制定的 jQuery:

$('#relatedinfo ul li a').html().replace('?</span>:','?</span>');

但这实际上并没有在 DOM 中替换它。如何让该字符串实际更改页面?

【问题讨论】:

    标签: javascript jquery replace


    【解决方案1】:

    我建议:

    $('#relatedinfo ul li a').html(function(index,html){
        return html.replace(/<\/span>(\:)/,'');
    });
    

    JS Fiddle demo.

    甚至:

    $('#relatedinfo ul li a').text(function(index,text){
        return text.replace(':','');
    });
    

    JS Fiddle demo.

    一种更新的方法是检查span 中的最后一个字符是否在['?','!','.'] 的数组中,如果是,则从nextSibling 的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(':','');
        }
    });
    

    JS Fiddle demo.

    参考资料:

    【讨论】:

    • 非常感谢您的回答,并为您花了这么长时间才回过头来表示歉意。答案是正确的,但我错误地提出了我的问题,因此解决方案不太适合我的问题。我有forked the fiddle,并且使用您提供的信息,计算出其中的大部分......只是无法弄清楚 if 语句中 OR 操作数的语法。我最终使用 != null 解决了它:)
    【解决方案2】:

    你也可以使用正则表达式:

    var rx = new RegExp('(?![^<&]+[>;])' + searchString, 'gi');
    
    $('#relatedinfo').html(function (i, html) {
       return html.replace(rx, '<b>$&</b>')
    });
    

    来源:jQuery to Find/Replace html text when not inside an html tag other than P, DIV, SPAN, TD

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-09-22
      • 2011-08-22
      • 2014-05-26
      • 2013-03-23
      • 2016-04-14
      • 1970-01-01
      相关资源
      最近更新 更多