【问题标题】:How can I create a loop that creates functions with data from an array?如何创建一个使用数组中的数据创建函数的循环?
【发布时间】:2016-02-04 08:15:35
【问题描述】:

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

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

【问题讨论】:

  • @Daan,一天结束,它们只附加在循环中;)
  • 使用class selector/any selector 将返回集合。
  • 你不能把所有的 rowid 值保存在一个变量中(可能是 b 数组)n 在控制器端传递

标签: javascript php arrays function loops


【解决方案1】:

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

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 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);
        }
    });
});

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

或者如果这些按钮是动态添加/删除的,您可能会在某个容器上使用事件委托。

【讨论】:

    猜你喜欢
    • 2018-04-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-01-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多