首页 > 解决方案 > 按钮 onclick 方法未传递元素 ID

问题描述

我一直在尝试动态生成页面上的按钮列表,每个按钮都有一个传递其 id (this.id) 的 onclick 方法。我知道我可以访问该方法本身,因为我已经测试了它的一个没有任何参数的版本。

代码的具体流程如下:我的应用程序调用 API (Spotify),并获取数据对象列表(在本例中为播放列表)以及访问代码。然后,它使用 onclick 方法为每个对象的页面添加一个按钮getData(this.id)。此方法包含在一个单独的 javascript 文件中,用于接收此 id,使用上述访问代码再次调用 API,然后隐藏具有指定 id 的按钮。但是,当您单击其中一个播放列表按钮时,绝对不会发生任何事情。相关代码如下。一些帮助将不胜感激。

客户端.js

if (hash.access_token) {
      $('#login_jumb').hide();
      $.get({url: '/nextpage', headers: {"Authorization": `Bearer ${hash.access_token}`}}, function(data) {
        // "Data" is the array of track objects we get from the API. See server.js for the function that returns it.
        console.log(data)

        var title = $('<h3 class="display-4">Your public Spotify playlists:</h3>');
        title.prependTo('#data-container');

        var tracks = new Array(data.items.length);
        // For each of the playlists, create an element
        data.items.forEach(function(playlist) {
          var playlistDiv = $('<button class="btn btn-dark button-pad " id="new"></button>');
          playlistDiv.text(playlist.name);
          playlistDiv.appendTo('#data-container ul');
          document.getElementById("new").id = playlist.name;

          var button = document.getElementById(playlist.name);
          button.setAttribute("onclick","getData(this.id)");
          button.title = button.id;
        });

      });
    }

检索数据.js

    function getData(id) {
            var token = localStorage.getItem("accessToken");

            $.get({url: '/getdata', headers: {"Authorization": `Bearer ${token}`}}, function(data) {
                console.log(id);

                document.getElementById(id).hide();

              });
        }

标签: javascripthtmlnode.js

解决方案


删除button.setAttribute("onclick","getData(this.id)");并将其添加到您的条件块之外

$(document).on("click", '#data-container button', function (e) {
    const id = $(this).attr('id')

    getData(id)
});

当你追加一个虚拟元素时,你应该参考文档对象来监听新元素事件


推荐阅读