2

我的代码使用 jquery 向页面添加元素,然后向其添加“点击”事件。代码是:

$('.photosItem').mouseover(function() {
        // Remove all existing comment buttons
        $('.reelPhotoPageCommentLink').remove();
        // Add a comment button
        var commentButton = "<div class='reelPhotoPageCommentLink'>";
        commentButton += "Comment";
        commentButton += "</div>";
        $(this).prepend(commentButton);
        // Add click event to comment button
        $('.reelPhotoPageCommentLink').click(function() {
            $('#editPopupForm').remove();
            // Get photo id
            var photoID = $(this).parent().attr('photo_id');
            var url = "get_photo_comment_form/" + photoID;
            $.ajax({ 
                url: url,
                type: "POST",
                success: function(data) {
                    // Add item after header
                    $('#header').after(data);
                }
            });
        });
    });

因此,当您将鼠标悬停在具有“photosItem”类的照片上时,会出现一个“评论”按钮。点击按钮弹出评论框。这在 Firefox 上运行良好,但我在 Chrome 上遇到了问题,它似乎没有接收到点击事件。当我悬停时它会添加评论按钮,但单击它不会做任何事情。控制台在任何阶段都没有错误。

我在 $('.reelPhotoPageCommentLink').click(function() { 之后添加了一个 console.log,它没有显示出来,所以看起来点击事件被忽略了。

任何人有任何想法我怎样才能让它工作?在 Firefox 中没问题,那里没有警告或错误。

谢谢!

4

3 回答 3

4

当您动态添加.reelPhotoPageCommentLink到 DOM 时,即在 DOM 加载之后,您需要委托事件处理程序。

$('.photosItem').on('click', '.reelPhotoPageCommentLink', function() {

});

虽然您的代码在某些浏览器上运行,但以上是正确的过程。

如果您将上面的click处理程序代码放在事件之外会更好mouseover,将任何事件绑定到另一个事件中并不是一个好主意。

完整代码如下所示:

// Add click event to comment button

 $('.photosItem').on('click', '.reelPhotoPageCommentLink', function() {
    $('#editPopupForm').remove();
    // Get photo id
    var photoID = $(this).parent().attr('photo_id');
    var url = "get_photo_comment_form/" + photoID;
    $.ajax({ 
        url: url,
        type: "POST",
        success: function(data) {
            // Add item after header
            $('#header').after(data);
        }
    });
});

$('.photosItem').mouseover(function() {
    // Remove all existing comment buttons
    $('.reelPhotoPageCommentLink').remove();
    // Add a comment button
    var commentButton = "<div class='reelPhotoPageCommentLink'>";
    commentButton += "Comment";
    commentButton += "</div>";
    $(this).prepend(commentButton);
});
于 2012-06-11T16:23:14.483 回答
1

在鼠标悬停时附加事件处理程序似乎是个坏主意。您可能应该使用委托事件编程模型,该模型将事件处理程序附加到 DOM 中的更高级别,并且可以处理动态添加的内容。例如

$('.photosItem').on('click', '.reelPhotoPageCommentLink', function(e) {

});
于 2012-06-11T16:25:23.783 回答
0

我最终放弃了这个。

相反,我在页面加载时生成了带有点击事件的按钮,但将它们隐藏起来。然后翻转显示按钮而不是生成它们。

感谢 codeparadox 和 Malevolence 的帮助。了解 jsfiddle 也很方便——我相信我会再次使用它。

于 2012-06-15T12:39:00.377 回答