JQuery:使用特定类在span后删除逗号

问题描述 投票:0回答:1

我试图弄清楚如何删除在一个类的跨度之后存在的逗号,如下所示:

<p>Red, green, <span class="no-comma">I don't wanna the next comma</span>, blue, yellow.</p>

到目前为止,我已经尝试过:

<script type="text/javascript">
    jQuery(document).ready(function(){
        var noCommas = jQuery('.no-comma').nextAll();
        noCommas = noCommas.replace(/,/g, '');
    });
</script>

...没有成功。

jquery
1个回答
3
投票

为此使用nextAll()的问题是它仅收集同级元素,而不是文本节点。

唯一可以与元素一起收集文本节点的jQuery方法是contents()

您可以使用基础的本地element.nextSibling,查看它是否是文本节点,并以逗号开头,如下所示:

$('.no-comma').each(function() {
  const next = this.nextSibling;
  if ( next && next.nodeType === 3 && next.textContent.startsWith(',') ) {
    next.textContent = next.textContent.replace(',', '');
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<p>Red, green, <span class="no-comma">I don't wanna the next comma</span>, blue, yellow.</p>

0
投票

另一种方法可以使用正则表达式:

var str = document.querySelectorAll('p')[0].innerHTML;
var reg = /[>]+[,]/g;
noCommas = str.replace(reg, '>');
document.querySelectorAll('p')[0].innerHTML = noCommas;
<p>Red, green, <span class="no-comma">I don't wanna the next comma</span>, blue, yellow.</p>
© www.soinside.com 2019 - 2024. All rights reserved.