Javascript 简单迭代DOM元素不起作用
这本应是一项简单的任务,但事实上我花了数小时来解决这个问题,我在谷歌上搜索并没有找到解决方案,基本上我想迭代dom元素(带ID的div),下面是我的代码: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
$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>