10

我正在使用“替换”功能来删除 div 中的所有非数字值。

似乎 Jquery 替换只影响第一个元素。

这是我的jQuery:

$('#comment').each(function() {
    var thz = $(this);
    var repl = thz.html(thz.html().replace(/\D+/g, ''));
});

HTML 代码:

<a id="comment1" href="#"> c2fđf011. </a>
<a id="comment1" href="#"> c20ff113. </a>
<a id="comment1" href="#"> c201gf76341. </a>

结果:

2011 c20ff113。c201gf76341。

我想要的结果是:

2011 20113 20176341

4

4 回答 4

30

您有重复的 id,这是无效的,并且 jQuery ID 选择器(或任何其他 id 选择器,如 document.getElementById 内部 jQuery 使用,因为具有 id 的元素被大多数浏览器索引并且是唯一的)将只返回第一个出现在 DOM 中。将其更改为 class 并查看它的工作:

$('.comment').each(function() { 
     var thz =  $(this); var repl =
     thz.html(thz.html().replace(/\D+/g, '')); 
});

HTML

<a class="comment1" href="#"> c2fđf011. </a> 
<a class="comment1" href="#">c20ff113. </a> 
<a class="comment1" href="#"> c201gf76341. </a>

顺便说一句,你的身份证是这样的:-

<a id="comment1" href="#"> c2fđf011. </a> 
<a id="comment2" href="#">c20ff113. </a> 
<a id="comment3" href="#"> c201gf76341. </a>

从属性选择器开始会帮助您(但实际上会减慢您的速度,因为这是一个属性选择器并且失去了使用 ID 的优势)。

$('[id^=comment]').each(function() { // While using this better give a container context $('[id^=comment]', 'container').each(function...
    var thz = $(this);
    var repl = thz.html(thz.html().replace(/\D+/g, ''));
});

演示

道德:ID 必须是唯一的

于 2013-06-03T03:50:12.950 回答
17

HTML 页面中的 ID 应该是唯一的

这就是它只针对找到的元素的第一个实例的原因。

用类替换元素

$('.comment').each(function() {
       // Your code
});
于 2013-06-03T03:49:40.377 回答
8
$('.comment').each(function() { var thz = $(this); var repl = thz.html(thz.html().replace(/\D+/g, '')); });

用 id 替换你的元素comment到一个类comment

如果您在元素上多次使用 ID,则选择器只会选择具有该 ID 的第一个元素。

但是当您改用 class 时,选择器将选择所有具有该类的元素。

于 2013-06-03T03:50:35.657 回答
4

如果您真的不想更改 html,则可以按属性使用选择器。但正如其他人所建议的那样,使用 class 而不是 id 是这里的最佳选择。

$('div[id="comment"]').each(function(){})
于 2013-06-03T03:58:38.440 回答