Я написал немного кода для обработки вставки комментария через AJAX. Как только вы ввели комментарий, получив HTML-код с сервера и используя .append()
, чтобы вставить его в DOM, похоже, что для нового элемента не было обработано событие .hover()
.JQuery - После .append, .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();
});
});
ПОЧЕМУ?
Почему? Потому что '$ ('div.comment [id^= комментарий _]'). Hover (...' только привязывает обработчик зависания к элементам, соответствующим этому селектору _ в тот момент, _ не для элементов, которые могли бы соответствовать ему в будущем. – nnnnnn
@ nnnnnn Как я могу сопоставить '$ ('div.comment [id^= комментарий _]'). hover (...' after' .append() '? –