[英]unable to break out of jquery each loop
I have a nested loop written in jquery and return false inside my child loop keeps appending the same text to the parent row. 我有一个用jquery编写的嵌套循环,并且在我的子循环内部返回false时,总是将相同的文本追加到父行中。 My code,
我的代码
$('#listingProducts ul.msRows li.msFullfillment').each(function(index) {
if(typeof $('#hfOrd'+index).val() != 'undefined'){
var $this = $(this);
var orderId = $('#hfOrd'+index).val();
// repainting logic
$('body').append(data);
$('#ajaxProducts ul.displayPoints li').each(function(index){
var $child = $(this);
if(typeof $('#hfAjaxOrderId'+index).val() != 'undefined'){
var ajaxOrderId = $('#hfAjaxOrderId'+index).val();
//alert(orderId+' '+ ' '+ajaxOrderId);
if(ajaxOrderId === orderId){
// replace the div here..
var anchorText = $child.find("#pointsLineAjax .redeem").text();
$this.find("#pointsLine .redeem").text(anchorText);
return false;
}
}
});
}
});
Return false inside child loop doesnt go back to the parent. 在子循环中返回false不会返回父项。 That doesnt seem to write it to the corresponding row.
那似乎没有将其写入相应的行。 What am i missing here..
我在这里想念什么..
Returning false
only breaks out of the inner loop in a jQuery loop, there is a good explanation for the reason in this answer . 返回
false
只打破了jQuery循环的内部循环,对此答案有一个很好的解释。
The problem here is that while you can return false from within the .each callback, the .each function itself returns the jQuery object.
这里的问题是,尽管您可以从.each回调中返回false,但.each函数本身将返回jQuery对象。 So you have to return a false at both levels to stop the iteration of the loop.
因此,您必须在两个级别上都返回一个false才能停止循环的迭代。 Also since there is not way to know if the inner .each found a match or not, we will have to use a shared variable using a closure that gets updated.
同样,由于没有办法知道内部.each是否找到匹配项,因此我们将不得不使用一个共享变量,该共享变量使用一个已更新的闭包。
Try the following: 请尝试以下操作:
$('#listingProducts ul.msRows li.msFullfillment').each(function(index) {
var continueLoop = true;
if($('#hfOrd'+index).length){
var $this = $(this);
var orderId = $('#hfOrd'+index).val();
// repainting logic
$('body').append(data);
$('#ajaxProducts ul.displayPoints li').each(function(index){
var $child = $(this);
if($('#hfAjaxOrderId'+index).length){
var ajaxOrderId = $('#hfAjaxOrderId'+index).val();
//alert(orderId+' '+ ' '+ajaxOrderId);
if(ajaxOrderId === orderId){
// replace the div here..
var anchorText = $child.find("#pointsLineAjax .redeem").text();
$this.find("#pointsLine .redeem").text(anchorText);
continueLoop = false;
return false;
}
}
});
};
return continueLoop;
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.