2014-01-17 56 views
0

我有一個用jquery編寫的嵌套循環,並且在我的子循環中返回false,從而將相同的文本附加到父行。我的代碼,每個循環都無法跳出jquery

$('#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不會返回到父級。這似乎並沒有寫入相應的行。我在這裏丟失什麼..

+0

什麼是'$( '#hfOrd' +指數).VAL()'? –

+0

創建一個小提琴來檢查發生了什麼。 –

+0

@ ling.s它是現有行中的orderid,我正在比較從具有orderid的ajax返回的行,如果兩者都相同,我將替換文本。 – coderman

回答

1

返回false只在jQuery循環中跳出內循環,有一個很好的解釋原因in this answer

的這裏的問題是,當你可以從 。每次回調中返回false,該功能。每個返回自己的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; 
}); 
+0

將嘗試... – coderman