用 jQuery 替换列表中的每个元素

Replace each element in a list with jQuery

试图用 <span>(x)</span> 替换列表元素中的 (x),但我做错了,它复制了第一个元素

我的代码是:

jQuery(document).ready(function($){
 "use strict";
 $(".widget_categories li").each(function(){  
  $(this).html($(".widget_categories li").html().replace(/(\([^)]+\))/, "<span></span>"));
 });
});

当您尝试替换 html 时,您可能想要获取单个元素,而不是所有元素。所以而不是

$(this).html($(".widget_categories li").html().replace(/(\([^)]+\))/, "<span></span>"));

改为

$(this).html($(this).html().replace(/(\([^)]+\))/, "<span></span>"));

示例(注意我转义了 span 标签只是为了更容易看到结果)

$(function(){
  $(".widget_categories li").each(function () {
    var newValue = $(this).html().replace(/(\([^)]+\))/, "&lt;span&gt;&lt;/span&gt;");
    $(this).html(newValue);
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<ul class="widget_categories">
  <li>foo (x) bar</li>
</ul>