我记得以前遇到过这个问题,但我不知道它出现在哪个项目上,也不知道我是如何解决它的。
我有一个 ajax“添加到收藏夹”按钮,而且我还有一个无限滚动,当您到达页面底部时,ajax 会加载页面。问题是 ajax 不适用于新附加的内容:
// Favorites
$('.res-list .star').click(function(){
var starLink = $(this);
var listItem = $(this).parent().parent();
if ($(starLink).hasClass('starred')) {
$(starLink).removeClass('starred');
} else {
$(starLink).addClass('starred');
}
$.ajax({
url: '/favorites/?id=' + $(starLink).attr('data-id'),
type: 'PUT',
success: function() {
if ($(starLink).hasClass('starred')) {
$(listItem).animate({
backgroundColor: '#FFF8E4'
}, 400);
} else {
$(listItem).animate({
backgroundColor: '#ffffff'
}, 400);
}
}
});
return false;
});
最佳答案
您需要现场事件
$('.res-list').on('click', '.star', function() {
// code here
});
或者使用 delegate()
$('.res-list').delegate('.star', 'click', function() {
// code here
});
关于javascript - 我的 ajax/jQuery 函数不适用于动态加载的分页内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10573431/