您可以把它放在一個循環,通過給予處理事情時可以關上不會改變,就像一個參數的函數叫你做:
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);
}
});
});
現在,單個處理程序處理所有的人。
或如果這些按鈕是動態添加/刪除的,則可以在某個容器上使用事件委託。
@Daan,一天結束時,它們僅附加在循環中;) – Rayon
使用'class selector' /'任何選擇器',它將返回集合。 – Rayon
難道你不能只保存一個變量的所有rowid值(可能b陣列)n在控制器端傳遞 – Dhara