关于以下函数,我在过去一小时中重写了十几次:
function show_history() {
$('.job.collapsed').click(function() {
$(this).removeClass('collapsed');
$(this).addClass('expanded');
$(this).children('.bottom').load('expand.php', function(){
$('.job.expanded').click(function() {
$(this).removeClass('expanded');
$(this).addClass('collapsed');
$(this).children('.bottom').html('');
$(show_history);
});
});
});
}
我最初称之为:
$(document).ready(function() {
$('#main').load('jobs.php', show_history);
});
当我第一次单击“.JOB”时,一个请求被发送到‘expand.php’,第二次单击也向‘expand.php’发送了一个请求——尽管‘.JOB’没有'.ollapsed' 类。第3次点击发送2次请求,第4次发送3次请求,第5次发送6次请求,第6次发送9次请求,第7次发送18次请求,第8次发送27次请求......我怎么才能解决这个问题?
更新:
我使用的解决方案,基于@mblase75的建议:
function show_history() {
$('.job.collapsed').live('click',function() {
$(this).removeClass('collapsed');
$(this).addClass('expanded');
$(this).children('.bottom').load('expand.php');
});
$('.job.expanded').live('click',function() {
$(this).removeClass('expanded');
$(this).addClass('collapsed');
$(this).children('.bottom').html('');
});
}
Try moving your .click
out of the callback and replace it with a .live("click")
handler:
$('.job.expanded').live('click',function() {
$(this).removeClass('expanded');
$(this).addClass('collapsed');
$(this).children('.bottom').html('');
$(show_history);
});
$(this).children('.bottom').load('expand.php');
I believe there is a possible flaw in the code: ".job.expanded" is a class which, I assume, is given to more than one item in the same page. Therefore, $(this) will apply to ALL the items in the page
possible fix:
$('.job.expanded').live('click',function() {
var $thisID = $(this.id);
$thisID.removeClass('expanded');
$thisID.addClass('collapsed');
$thisID.children('.bottom').html('');
$(show_history);
});
Oh yes, I have lost a bunch of hair on similar code fixing myself and hope have saved you some of your own.....