如何创建一个循环,使用数组中的数据创建函数


How can I create a loop that creates functions with data from an array?

如何在循环中做这样的事情?还是有更好的方法

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

你可以把它放在一个循环中,通过给处理程序一些不会改变的东西来关闭,比如你所做的函数调用中的参数:

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,但可填充] 或 Array.prototype.slice.call(rowid) 轻松使其成为一个数组。

更多细节在这里:循环内的JavaScript闭包 - 简单的实际示例

但是,在这种特殊情况下,您不需要创建一堆处理程序函数;将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);
        }
    });
});

现在,一个处理程序可以处理所有这些问题。

或者,如果这些按钮是动态添加/删除的,则可以对某些容器使用事件委派。