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



这应该是一件容易的事,但实际上我花了几个小时来解决这个问题,我用谷歌搜索了一下,还没有找到解决方案,基本上我想迭代 dom 元素(div 带有 ID),这是我的代码:

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

在内容上:

   <div id="pinlocation">Test1</div>
   <div id="pinlocation">Test2</div>

我在这里复制错误:http://www.doxadigital.com/scrape/dummy.php

如您所见,此脚本无法获得第二个"精确定位"。知道我做错了什么吗?

多谢

ID应该

是一个唯一的标识符。要么将其更改为类,要么为其提供不同的 ID。

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

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

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

现在应该可以正常工作。

您的 HTML 无效,因为您对多个元素使用了相同的 ID。 这就是您的代码不会迭代第二个 ID 的原因。

见 http://www.w3.org/TR/REC-html40/struct/global.html#h-7.5.2

而是对元素使用类。

两个控件具有相同的 id,不应如此。您可以向下塑造选择器以进行迭代,但this is bad practice and must not be used unless you have no other option . Its better to put some class in both and using class selector .

改变

$j("#pinlocation")

$j("[id=pinlocation]")

您的代码

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

使用类选择器(推荐)

  <div id="pinlocation1" class="someclass">Test1</div>
  <div id="pinlocation2" class="someclass">Test2</div>

$j(document).ready(function(){
    $j(".someclass").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>

铌。所有 ID 都应该是唯一的。

最新更新