点击适用于dom中最初加载的元素,但是当我尝试单击最近添加的项时,它不起作用。我尝试了.live
,.delegate
和.on
,但它们根本不起作用。这是代码:
我使用了它并且它不起作用,它仍然会刷新页面:
$('.forms').on('click', '.button-like', function() {
var $parent = $(this).parent('.forms');
var $thisItem = $parent.find('.button-like');
console.log($parent);
$(this).submit(function () {
var data = {
"action": "like"
};
data = $parent.serialize() + "&" + $.param(data);
var itemId = $parent.find('input.id').val();
$.ajax({
type: "POST",
url: "/actions/",
data: data,
success: function (data) {
console.log('Like submitted successfully sent');
//$thisItem.addClass('isliked');
$thisItem.after('<button class="ajax instabtn button-unlike unlike icon-heart" type="submit" name="action" value="Unlike"></button>');
$thisItem.remove();
}
});
return false;
});
$(this).submit();
});
以上代码对页面中新添加的项目根本不起作用,它会不断刷新页面吗?
以下是您感兴趣的附加代码:
success: function(data) {
// Output data
$.each(data.images, function(i, src) {
var $content = $('<article class="instagram-image"><form id="'+ data.images[i].data_token +'" class="forms status-'+ data.images[i].data_like +'" action="'+base+'" method="post"><a class="fancybox" href="'+ data.images[i].data_link +'"><img alt="' + data.images[i].data_text + '" src="' + data.images[i].data_url + '" alt="' + data.images[i].data_text + '" /></a><input type="hidden" name="id" value="'+ data.images[i].data_id +'"><p>'+ data.images[i].data_likes +'</p></form></article>');
$('section#images').append($content);
if( $content.find('form').hasClass("status-false") ){
$content.find('form').addClass("notLiked");
//$('.notLiked').find('button.unlike').hide();
$content.find('form a').after('<button class="ajax instabtn button-like like icon-heart" type="submit" name="action" value="Like"></button>');
}
if( $content.find('form').hasClass("status-true") ){
$content.find('form').addClass("Liked");
//$('.Liked').find('button.like').hide();
$content.find('form a').after('<button class="ajax instabtn button-unlike unlike icon-heart" type="submit" name="action" value="Unlike"></button>');
}
});
// Store new maxid
$('#more').data('maxid', data.next_id);
}
我已经尝试了一切,它仍然无法正常工作。我想知道这是错误的逻辑吗?
干杯, 标记
答案 0 :(得分:0)
这可能会起作用吗?
$('.forms').submit(function() {
var $parent = $(this);
var $button = $parent.find('.button-like');
var data = {
"action": "like"
};
data = $parent.serialize() + "&" + $.param(data);
var itemId = $parent.find('input.id').val();
$.ajax({
type: "POST",
url: "/actions/",
data: data,
success: function (data) {
console.log('Like submitted successfully sent');
//$thisItem.addClass('isliked');
$button.after('<button class="ajax instabtn button-unlike unlike icon-heart" type="submit" name="action" value="Unlike"></button>');
$button.remove();
}
});
return false;
});