2016-02-04 150 views
-2

如何在循環中做這樣的事情? 還是有更好的方法來做到這一點?如何創建一個用數組中的數據創建函數的循環?

 $('#btndelete' + rowid[i]).click(function(){ 
 
     $.ajax({ 
 
     type: "POST", 
 
     url: "delete.php?id=rowid[i]", 
 
     success: function(a) { 
 
       $('#div-content').html(a); 
 
     } 
 
    }); 
 
});

+0

@Daan,一天結束時,它們僅附加在循環中;) – Rayon

+0

使用'class selector' /'任何選擇器',它將返回集合。 – Rayon

+0

難道你不能只保存一個變量的所有rowid值(可能b陣列)n在控制器端傳遞 – Dhara

回答

0

可以把它放在一個循環,通過給予處理事情時可以關上不會改變,就像一個參數的函數叫你做:

rowid.forEach(function(value) { 
    $('#btndelete' + value).click(function() { 
     $.ajax({ 
      type: "POST", 
      url: "delete.php?id=" + value, 
      success: function(a) { 
       $('#div-content').html(a); 
      } 
     }); 
    }); 
}); 

(如果rowid不是數組,可以很容易使之與一個Array.from [ES2015,但shimmable]或Array.prototype.slice.call(rowid)。)

更多細節在這裏:JavaScript closure inside loops – simple practical example

但是,在這種特殊情況下,您不需要創建一堆處理函數;把rowid[i]的元素,然後使用一個處理程序爲所有這些:

rowid.forEach(function(value) { 
    $("#btndelete" + value).data("rowid", value); 
}); 
$("[id^=btndelete]").click(function() { 
    $.ajax({ 
     type: "POST", 
     url: "delete.php?id=" + $(this).data("rowid"), 
     success: function(a) { 
      $('#div-content').html(a); 
     } 
    }); 
}); 

現在,單個處理程序處理所有的人。

如果這些按鈕是動態添加/刪除的,則可以在某個容器上使用事件委託。