拼接JSON数组JavaScript [英] Splice JSON array JavaScript

查看:103
本文介绍了拼接JSON数组JavaScript的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我创建了一个用于对javascript数组重用拼接功能的函数,但是,一旦运行它,就无法重用.

I created a function for reusing the splice feature for javascript arrays however, after I run it once, it cannot be reused.

var removePerson = function(d, person_id) { 
  var person_index = d.findIndex(i => i.id == person_id);
  d.splice(person_index, 1);
  return d;
};

我没有收到控制台错误.我不知道如何调试它.这是我的 JSFiddle .

I am not getting console errors. I do not know how to debug it. Here is my JSFiddle.

如果运行示例,您将看到可以从列表中删除任何1个人,但是当您尝试删除其余2个人中的任何一个时,则什么也没有发生(例如,控制台错误,控制台响应).知道如何支持removePerson()函数的重用吗?

If you run the example, you will see you can remove any 1 person from the list, but when you try to remove either of the remaining 2, nothing happens (e.g. console errors, console response). Any idea how I can support reuse for my removePerson() function?

推荐答案

由于populateList的工作方式,您的解决方案无法正常工作.

Your solution doesn't work because of how your populateList works.

在您的populateList中,有一行:

$('#load').empty();

此行清空表,并删除与click事件监听器关联的按钮.

This line empties the table and removes the buttons attached with click event listener.

然后,您添加一个全新的button.delete,它没有任何事件侦听器附加.

Then, you add completely new button.delete, which aren't attached with any event listener.

要解决此问题,可以将.on()放入populateList函数.

To solve this, you can put your .on() into populateList function.

var populateList = function(d) {
    $("#load").empty();
    var new_rows;
    for(var i = 0; i < d.length; i++) {
        new_rows += "<tr>" + 
            "<td>" + d[i].id + "</td>" +
            "<td>" + d[i].name + "</td>" +
            "<td>" + d[i].phone + "</td>" +
            "<td><button class='delete' data-id='" + d[i].id + "'>delete</button></td>" +
            "</tr>";
    }
    $("#load").append(new_rows);

    // delete event
    $(".delete").on("click", function() {
      var delete_sel = $(this).attr("data-id");
      populateList(removePerson(d, delete_sel));
    });
};

这是一个正常工作的 jsFiddle .

或者,您可以使用此答案(这是一个更清洁的解决方案imo).

Alternatively, you can use solution from this answer (which is a cleaner solution imo).

$("table").on("click",".delete", function() {
  var delete_sel = $(this).attr("data-id");
  populateList(removePerson(data, delete_sel));
});

关于他的答案为何可在 jQuery文档上进行的更多解释(请查看selector参数).

More explanation on why his answer works on jQuery documentation (Look at the selector parameter).

这篇关于拼接JSON数组JavaScript的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆