【问题标题】:jQuery to replace characters in string for multiple instances of a classjQuery为类的多个实例替换字符串中的字符
【发布时间】:2013-10-26 10:08:42
【问题描述】:

我有一个名为 product-attributes 的 css 类,它在一个页面上多次使用,每个类都包含不同的字符串。所有这些字符串都包含我只想用 br 标签替换的逗号。我想出了下面的代码,但这会将所有字符串替换为完全相同的字符串(来自更正第一个类实例)。

$('.product-attributes').html($('.product-attributes').html().replace(/,/g,'<br />'));

我哪里错了?

非常感谢

【问题讨论】:

    标签: jquery css string replace


    【解决方案1】:

    使用选择器调用html() 将仅针对选择器返回的first 元素调用。您需要使用each() 替换所有出现的字符串。

    $('.product-attributes').each(function(){    
        $(this).html($(this).html().replace(/,/g,'<br />'));    
    });
    

    【讨论】:

      【解决方案2】:

      您需要使用.each() 在类的每个实例上调用该函数。否则,您只需将该类的每个元素的 html 更改为该类的第一个实例的 html。如上所述。

      $('.product-attributes').each(function(){
          $(this).html($(this).html().replace(/,/g,'<br />'));
      });
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2016-03-24
        • 2012-11-14
        • 1970-01-01
        • 1970-01-01
        • 2017-12-01
        • 2016-02-29
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多