javascript - 如何使用 JQuery 设置 onclick 监听器

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

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

最佳答案

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

onclick: function() { onPostClick(curPostId); }

此外,您需要将 curPostId 保存在闭包中,否则您将获得所有元素的相同值(请参阅 Javascript infamous Loop issue? )。所以应该是:

onclick: (function(curPostId) {
            return function () { onPostClick(curPostId); };
         })(curPostId)

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

onclick: onPostClick

您还可以通过为您的图像提供一个类并使用事件委托(delegate)来避免整个问题。请参阅Event binding on dynamically created elements? .

关于javascript - 如何使用 JQuery 设置 onclick 监听器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24297190/

相关文章:

javascript - 从javascript/html播放音频时设置自定义元数据(Control Center iOS)

javascript - 传单.js : detecting when map finishes zooming

javascript - 我可以修改使用 window.open 加载的外部 URL 的 HTML DOM 吗?

javascript - 如何在浏览器中预取返回 JSON 格式数据的 ajax 调用

jquery - 带有鼠标悬停动画的重复 jQuery

javascript - Angularjs doclick更改当前div的类

javascript - 使用 Firebug 或 Google Chrome 识别哪个 Javascript 执行调用

c# - 如何制作事件字典?

objective-c - Objective-C : How to use addTarget:action:forControlEvents: method?

qt - QML - 捕获子对象的所有 UI 事件