Jquery - 在.append之后,.hover在其他元素上不起作用

Ang*_*edi 0 javascript ajax jquery appendchild

我写了一些代码来处理通过AJAX插入注释.一旦输入注释,从服务器接收到HTML并用于.append()将其插入DOM,似乎不会处理.hover()新项目的事件.

有代码:

/**
 * This code manage insert comment with ajax
 **/

$(document).ready(function() 
{
    $('form[id^=insert_comment_for_product_]').submit(function (event)
    {
        event.preventDefault();

        var productId = $(this).attr('id');
        var productIdClear = productId.substr(productId.lastIndexOf('_', 0) - 1, productId.length);

        var textarea = $('#' + $(this).attr('id') + ' textarea').val();
        var textareaId = $('#' + $(this).attr('id') + ' textarea').attr('id');
        var token = $('#' + $(this).attr('id') + ' input#user_comment_product__token').val();

        var gif = $(this).parent('div').children('img.insert_comment_img');
        $(gif).show();

        $.post($(this).attr('action'),
        {
            'id': productIdClear.toString(),
            'user_comment_product[comment]': textarea,
            'user_comment_product[_token]' : token
        },
        function(data) 
        {
            $('div.product_comment>div').append(data);
            $('#' + textareaId).val(' ');
            $(gif).hide();
        });

    });
   /**
    * This is the function that no work afert .append()
    **/


    $('div.comment[id^=comment_]').hover(function()
    {
        var commentId = $(this).attr('id');

        $('#' + commentId + ' img.comment_delete').show();

        $('#' + commentId + ' img.comment_delete').click(function(event)
        {
            event.stopImmediatePropagation();
            commentId = commentId.substr(commentId.lastIndexOf('_') + 1, commentId.length);

            $.post("../../../user/comment/delete",
            {
                'id': commentId.toString()
            },
            function(data) 
            {
                if(data.responseCode == 200)
                {
                    $('div#comment_' + commentId).hide();
                }
            });
        })

    },
    function ()
    {
        var commentId = $(this).attr('id');

        $('#' + commentId + ' img.comment_delete').hide();
    });
});
Run Code Online (Sandbox Code Playgroud)

为什么?

cla*_*lav 6

您可以使用该on函数绑定到动态添加的元素,而不是这样:

$('div.comment[id^=comment_]').hover(function()
Run Code Online (Sandbox Code Playgroud)

做这个:

$(document).on('mouseover', 'div.comment[id^=comment_]', function(e) {
    // code from mouseover hover function goes here
});

$(document).on('mouseout', 'div.comment[id^=comment_]', function(e) {
     // code from mouseout hover function goes here
});
Run Code Online (Sandbox Code Playgroud)