[英]jQuery each() only selects last value
I have 2 list. 我有2个清单。
the first list holds all data. 第一个列表保存所有数据。 The other one are placeholders. 另一个是占位符。 And I have a button to take the default values. 我有一个按钮可以采用默认值。 Which clones the first list into the placeholders. 将第一个列表克隆到占位符中。
Now I'm using this code to alert
all the found data-id
's. 现在,我正在使用此代码来alert
所有找到的data-id
。 Which works fine. 哪个工作正常。
But when I'm trying to paste those data-attributes onto the placeholders it always pastes the last value in each placeholder. 但是,当我尝试将这些数据属性粘贴到占位符上时,它总是将最后一个值粘贴到每个占位符中。
$(".default").click(function() {
$("li.to-drag").each(function(index) {
$("li.placeholder").addClass("dropped");
var clone = $(this).clone();
var day = $(this).attr("data-id");
$("li.placeholder").each(function(){
$("li.placeholder").attr("data-id", index);
});
clone.hide().appendTo("." + index).fadeIn(1500);
});
var dropped = $(".dropped").length;
var original = $(".placeholder").length;
if (dropped === original) {
$("li.placeholder").removeClass(blank_placeholder);
$("#dropzone").append('<li class="placeholder blank" data-id="" data-order=""></li>');
init();
}
});
How can I solve this? 我该如何解决?
SOLUTION : 解决方案 :
I had to do a second each()
loop outside the other one which iterated the .to-drag
class. 我不得不在另一个迭代.to-drag
类的循环之外执行第二个each()
循环。
$("li.placeholder").each(function(){
var day = $(this).children().attr("data-id");
$(this).attr("data-id", day);
});
In your .each()
loop, you have to use $(this)
, otherwise you will change everything everytime the loop repeats. 在您的.each()
循环中,您必须使用$(this)
,否则每次循环重复时都将更改所有内容。
So just change the following part of your code: 因此,只需更改代码的以下部分:
$("li.placeholder").each(function(){
$(this).attr("data-id", index);
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.