[英]unable to break out of jquery each loop
我有一個用jquery編寫的嵌套循環,並且在我的子循環內部返回false時,總是將相同的文本追加到父行中。 我的代碼
$('#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;
}
}
});
}
});
在子循環中返回false不會返回父項。 那似乎沒有將其寫入相應的行。 我在這里想念什么..
返回false
只打破了jQuery循環的內部循環,對此答案有一個很好的解釋。
這里的問題是,盡管您可以從.each回調中返回false,但.each函數本身將返回jQuery對象。 因此,您必須在兩個級別上都返回一個false才能停止循環的迭代。 同樣,由於沒有辦法知道內部.each是否找到匹配項,因此我們將不得不使用一個共享變量,該共享變量使用一個已更新的閉包。
請嘗試以下操作:
$('#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.