【问题标题】:Jquery replace for eachJquery替换每个
【发布时间】:2012-07-05 09:04:24
【问题描述】:

我想用 span 标签替换每个链接中的每个“New”。

对吗?

$("a:contains('New')").each(function () {
                 $(this).html($(this).html().replace("New", "<span class='new'>New</span>"));
        });

【问题讨论】:

    标签: javascript jquery replace each


    【解决方案1】:

    正则表达式:工作演示 http://jsfiddle.net/WujTJ/

    g = /g 修饰符确保所有出现的“替换”

    i - /i 使正则表达式匹配不区分大小写。

    一本好书:如果你喜欢:http://www.regular-expressions.info/javascript.html

    请试试这个:

    希望这个帮助:)

    另外请注意,您可能不需要检查它是否包含New,因为如果需要,正则表达式会更改:

       // $("a:contains('New')").each(function () { // NOT sure if you need this
                         $(this).html($(this).html().replace(/New/g, "<span class='new'>New</span>"));
          //      });
    

    【讨论】:

      【解决方案2】:

      您是否尝试过您的代码?
      如您所见here,它运行良好,唯一的问题是您忘记使用g 修饰符替换所有"New" 出现。

      另一个问题是您不需要每个循环,因为您可以看到以下代码执行相同的操作。
      不同之处在于不必循环并获取项目 html 两次

      $("a:contains('New')").html(function(i, text) {
          return text.replace(/New/g, '<span class="new">New</span>');
      });
      

      demo

      【讨论】:

        【解决方案3】:

        这也是一个非常简单的方法:

        $("a:contains('New')").each(function() {
            $(this).html(function(index, text) {
                return text.replace('New', '<span class="new">New</span>');
            });
        });
        

        从这里:JavaScript/jQuery: replace part of string?

        编辑:

        Ricardo Lohmann的回答比较好,杀死each()函数:

        $("a:contains('New')").html(function(i, text) {
            return text.replace(/New/g, '<span class="new">New</span>');
        });
        

        【讨论】:

          猜你喜欢
          • 2010-11-24
          • 2013-05-19
          • 1970-01-01
          • 2016-06-16
          • 1970-01-01
          • 2015-06-24
          • 2013-03-05
          • 1970-01-01
          • 2014-03-25
          相关资源
          最近更新 更多