如何使用 JQuery 设置 onclick 监听器

cha*_*wow 1 javascript jquery events onclick

我正在尝试从 JSON 数组动态创建一个列表图像,该数组将在单击其中一张图像时调用 JavaScript 函数。该函数将向服务器发送请求,标记该图像。我目前有以下内容:

        var GLOBAL_POST_ID_LIST = [];
    function createList(jsonData) {
        for (var i = 0; i < jsonData.posts.length; i++) {
            var curPostId = jsonData.posts[i].post_id;

            // Check if the current post is in the list
            if ($.inArray(curPostId, window.GLOBAL_POST_ID_LIST) < 0) {
                jQuery('<img/>', {
                    id: curPostId,
                    src: jsonData.posts[i].image_url,
                    selected: false,
                    onclick: onPostClick(curPostId)
                }).appendTo('#postDiv');
                // At the current post to the list
                window.GLOBAL_POST_ID_LIST.push(curPostId);
            }
        }
    }
Run Code Online (Sandbox Code Playgroud)

但是,onclick 函数会在对象初始化时立即调用,而不是在单击对象时调用。当任何给定的帖子初始化时,如何才能使用正确的 post_id 调用 onPostClick?

Bar*_*mar 5

您需要将其包装在一个函数中:

onclick: function() { onPostClick(curPostId); }
Run Code Online (Sandbox Code Playgroud)

另外,您需要curPostId保存在闭包中,否则您将获得所有元素的相同值(请参阅Javascript臭名昭著的循环问题?)。所以应该是:

onclick: (function(curPostId) {
            return function () { onPostClick(curPostId); };
         })(curPostId)
Run Code Online (Sandbox Code Playgroud)

onPostClick但是,为什么首先需要传递 ID 参数呢?jQuery 自动绑定this到事件处理程序中的事件目标,因此onPostClick应该能够使用this.id它来获取 ID。如果你修复这个函数来做到这一点,你可以这样写:

onclick: onPostClick
Run Code Online (Sandbox Code Playgroud)

您还可以通过为您的图像提供一个类并使用事件委托来避免整个问题。看到动态创建的元素上的事件绑定了吗?


bum*_*paw 5

你可以使用这个:

$("#yourId").click(function(){...});
Run Code Online (Sandbox Code Playgroud)