Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/logging/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 为什么Jquery只影响第一个div元素?_Javascript_Jquery_Html - Fatal编程技术网

Javascript 为什么Jquery只影响第一个div元素?

Javascript 为什么Jquery只影响第一个div元素?,javascript,jquery,html,Javascript,Jquery,Html,我正在使用“replace”函数删除div中的所有非数值 jqueryreplace似乎只影响第一个元素 以下是我的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

我正在使用“replace”函数删除div中的所有非数值

jqueryreplace似乎只影响第一个元素

以下是我的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


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

$('.comment').each(function() { var thz = $(this); var repl = thz.html(thz.html().replace(/\D+/g, '')); });
这就是为什么它只针对找到的元素的第一个实例

元素替换为class

$('.comment').each(function() {
       // Your code
});

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

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

道德:ID必须是唯一的

$('.comment').each(function() { var thz = $(this); var repl = thz.html(thz.html().replace(/\D+/g, '')); });
用id
comment
将ur元素替换为类
comment

如果在元素上多次使用ID,选择器将仅拾取具有该ID的第一个元素


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

如果您确实不想更改html,则可以使用属性选择器。但正如其他人所建议的,在这里使用类而不是id是最好的选择

$('div[id="comment"]').each(function(){})

我想和大家分享的是,这是可能的。
$('.comment').each(function() { var thz = $(this); var repl = thz.html(thz.html().replace(/\D+/g, '')); });
$('div[id="comment"]').each(function(){})