[英]Jquery - After .append, .hover on other element not working
我寫了一些代碼來處理通過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();
});
});
為什么?
您可以使用on
函數綁定到動態添加的元素,而不是此:
$('div.comment[id^=comment_]').hover(function()
做這個:
$(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
});
.hover()在您的追加發生之前就已綁定,因此該事件不在該項目上。 您需要對mouseenter和mouseleave都使用.on(),以使其正常工作。 請參閱此處的“其他說明”部分: http : //api.jquery.com/on/
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.