我使用 jQuery/PHP/MySql 在页面上加载 Twitter 搜索结果,但仅限于前 20 个搜索结果。
当用户滚动页面并点击页面底部时,会加载并显示另外 20 个结果。
我已经实现了一个投票系统,因此可以对这些特定的推文进行上下投票。
但是,当加载滚动结果时,此功能将停止对 ajax 加载的结果起作用,但会继续对前 20 个结果起作用。
这是在滚动时获取新结果的 jQuery:
j(window).scroll(function(){
if (j(window).scrollTop() == j(document).height() - j(window).height()){
j.ajax({
url: "older.php?oldest="+oldestName+"",
cache: false,
success: function(html){
j(".older").html(html);
j('.tweets ul li').removeClass( 'last_item' );
j('.older ul > *').clone().hide().appendTo('.tweets ul').slideDown();
}
})
}
});
以及设置投票的 jQuery:
$("a.vote_up").click(function(){
//get the id
the_id = $(this).attr('id');
// show the spinner
$(this).parent().html("<img src='images/spinner.gif'/>");
//fadeout the vote-count
$("span#votes_count"+the_id).fadeOut("fast");
//the main ajax request
$.ajax({
type: "POST",
data: "action=vote_up&id="+$(this).attr("id"),
url: "vote.php",
success: function(msg) {
$("span#votes_count"+the_id).html(msg);
//fadein the vote count
$("span#votes_count"+the_id).fadeIn();
//remove the spinner
$("span#vote_buttons"+the_id).remove();
}
});
});
HTML 标记:
<li id='1283009589'>
<a class='imglink' target='_blank' href='link'>
<img src='link'alt='howtomoodle' title='howtomoodle' />
</a>
<a class='userlink' target='_blank' href='http://twitter.com/jim' alt='jim' title='jim'>jim</a>
Screenpresso - free screen capture software http://post.ly/uFxt #moodle || 28-08-2010 16:33
<span class='votes_count' id='votes_count22361731118'>Votes:0</span>
<span class='vote_buttons' id='vote_buttons22361731118'>
<a href='javascript:;' class='vote_up' id='22361731118'></a>
<a href='javascript:;' class='vote_down' id='22361731118'></a>
</span>
</li>
有谁知道为什么加载旧结果时不允许单击投票和否决按钮,或者至少 .click 事件不起作用。
最佳答案
那是因为“a.vote”的“click”事件在站点加载时绑定(bind)一次。当您加载新内容(接下来的 20 个结果)时,不会调用 $(document).ready 。看看 $.live 方法 http://api.jquery.com/live/这正是您所需要的:)
关于php - 使用 Ajax 时 jQuery 的奇怪问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3591469/