Jquery每个选择器索引不递增
我有以下html divJquery每个选择器索引不递增,jquery,each,Jquery,Each,我有以下html div <div id="sentencesDiv"> </div> 它总是将“img0”添加为id。 我不明白是什么问题 我想要这样的输出 <div id="sentencesDiv"> <div id="somekey1"> <input type="checkbox" /> <img class="correctWrong" alt="image" style="width: 42px; height:
<div id="sentencesDiv">
</div>
它总是将“img0”添加为id。
我不明白是什么问题
我想要这样的输出
<div id="sentencesDiv">
<div id="somekey1">
<input type="checkbox" />
<img class="correctWrong" alt="image" style="width: 42px; height: 42px;" id="img0">
</div>
<div id="somekey2">
<input type="checkbox" />
<img class="correctWrong" alt="image" style="width: 42px; height: 42px;" id="img1">
</div>
<div id="somekey3">
<input type="checkbox" />
<img class="correctWrong" alt="image" style="width: 42px; height: 42px;" id="img2">
</div>
......
</div>
和
$('#sentencesDiv div').each(function(index,value){});
多次出现的元素在其上使用 所以,使用这个来实现您的需求
$('#sentencesDiv div').each(function(index,value){
jQuery('<input/>', {
class : "ch",
type : "checkbox"
}).appendTo(mydiv);
jQuery('<img/>', {
class : "correctWrong",
alt : 'image',
width : '42px',
height :'42px',
id : 'img'+index
}).appendTo(mydiv);
});
$('#语句sdiv div')。每个(函数(索引、值){
jQuery(“”{
类别:“ch”,
键入:“复选框”
}).附录(mydiv);
jQuery(“”{
课堂:“纠正错误”,
alt:'图像',
宽度:“42px”,
高度:'42px',
id:'img'+索引
}).附录(mydiv);
});
因为您想在
侧边#语句sdiv
元素中添加代码,所以需要使用
// for all direct child elements of #sentencesDiv
$('#sentencesDiv > div').each(function(index,value){
// your code goes here
});
选择器(如“#sentencesDiv”)的.each()
操作最多运行一次内部函数,这就是索引
始终为零的原因
您可以将代码全部移出.each()
,然后使图像id取决于键
变量,而不是索引
var mydiv =jQuery('<div/>', {
id : key,
text: sentences[key], // key of sentence BDM4 is here
})
jQuery('<input/>', {
class : "ch",
type : "checkbox"
}).appendTo(mydiv);
jQuery('<img/>', {
class : "correctWrong",
alt : 'image',
width : '42px',
height :'42px',
id : 'img' + key
}).appendTo(mydiv);
mydiv.appendTo('#sentencesDiv');
var mydiv=jQuery(“”{
id:钥匙,
text:句子[键],//这里是BDM4句子的键
})
jQuery(“”{
类别:“ch”,
键入:“复选框”
}).附录(mydiv);
jQuery(“”{
课堂:“纠正错误”,
alt:'图像',
宽度:“42px”,
高度:'42px',
id:'img'+键
}).附录(mydiv);
mydiv.附录(“#语句sdiv”);
请使用$(“#sentencesDiv')共享这一部分。每个只会循环一次,因为id#sentencesDiv
是唯一的,我认为您可能必须使用后面的$('#sentencesDiv div')。每个从您的代码中,它肯定不会是$(“#sentencesDiv')。每个。这很可能是第二种情况,但您尚未显示如何生成
。
$('#sentencesDiv div').each(function(index,value){
jQuery('<input/>', {
class : "ch",
type : "checkbox"
}).appendTo(mydiv);
jQuery('<img/>', {
class : "correctWrong",
alt : 'image',
width : '42px',
height :'42px',
id : 'img'+index
}).appendTo(mydiv);
});
// for all direct child elements of #sentencesDiv
$('#sentencesDiv > div').each(function(index,value){
// your code goes here
});
var mydiv =jQuery('<div/>', {
id : key,
text: sentences[key], // key of sentence BDM4 is here
})
jQuery('<input/>', {
class : "ch",
type : "checkbox"
}).appendTo(mydiv);
jQuery('<img/>', {
class : "correctWrong",
alt : 'image',
width : '42px',
height :'42px',
id : 'img' + key
}).appendTo(mydiv);
mydiv.appendTo('#sentencesDiv');