Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/ssl/3.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 简单迭代DOM元素不起作用_Javascript_Jquery_Dom - Fatal编程技术网

Javascript 简单迭代DOM元素不起作用

Javascript 简单迭代DOM元素不起作用,javascript,jquery,dom,Javascript,Jquery,Dom,这本应是一项简单的任务,但事实上我花了数小时来解决这个问题,我在谷歌上搜索并没有找到解决方案,基本上我想迭代dom元素(带ID的div),下面是我的代码: $j(document).ready(function(){ $j("#pinlocation").each(function(index){ alert(index+":"+$j(this).text()); }); }); 关于内容: <div id="pinlocation">Tes

这本应是一项简单的任务,但事实上我花了数小时来解决这个问题,我在谷歌上搜索并没有找到解决方案,基本上我想迭代dom元素(带ID的div),下面是我的代码:

$j(document).ready(function(){
    $j("#pinlocation").each(function(index){
        alert(index+":"+$j(this).text());
    });

});
关于内容:

   <div id="pinlocation">Test1</div>
   <div id="pinlocation">Test2</div>
Test1
测试2
我在这里重复这个错误:

如您所见,此脚本无法获取第二个“pinlocation”。知道我出了什么问题吗


非常感谢

您对两个控件具有相同的id,但不应如此。您可以将选择器简化为迭代,但
这是一种糟糕的做法,除非您没有其他选项,否则不能使用它
最好将一些类同时放入并使用类选择器

改变

$j("#pinlocation")

$j("[id=pinlocation]")
您的代码

$j(document).ready(function(){
    $j("[id=pinlocation]").each(function(index){
        alert(index+":"+$j(this).text());
    });    
});
使用类选择器(推荐)

Test1
测试2
$j(文档).ready(函数(){
$j(“.someclass”)。每个(函数(索引){
警报(索引+”:“+$j(this.text());
});
});

ID应该是唯一的标识符。要么将其更改为类,要么给它们不同的id。

这里的问题很简单,您不能有两个id相同的元素,第二个元素将被忽略

您可以尝试将
id=“pinlocation”
更改为
class=“pinlocation”
,然后执行以下操作:

$j(document).ready(function(){
    $j(".pinlocation").each(function(index){
        alert(index+":"+$j(this).text());
    });
});

这是一个非常简单的解决方案,将您的id更改为类

$j(document).ready(function(){
    $j(".pinlocation").each(function(index){
        alert(index+":"+$j(this).text());
    });

});
<div class="pinlocation">Test1</div>
$j(文档).ready(函数(){
$j(“.pinlocation”)。每个(函数(索引){
警报(索引+”:“+$j(this.text());
});
});
测试1

注意。所有ID都应该是唯一的。

您的html无效,因为您对多个元素使用了相同的ID。这就是为什么代码没有对第二个id进行迭代


相反,使用类来表示元素。

事实上,您为两个不同的事物提供相同的标识符并不是一件好事。两个元素具有相同的ID是无效的。
ID
必须是唯一的,请使用类
class=“pinlocation”
“.pinlocation”
作为选择器为什么建议这样一种不好的做法?在DOM.OMG中不应该有两个ID相同的元素,经过多年的编码,我以前从来都不知道这个规则。。。谢谢你,伙计
$j(document).ready(function(){
    $j(".pinlocation").each(function(index){
        alert(index+":"+$j(this).text());
    });

});
<div class="pinlocation">Test1</div>