我的代码正在工作,但需要我单击两次才能激活我的链接(一次用于单击事件,一次用于切换事件。)我该怎么做才能做到这一点,这样我只需单击一次,以便切换会自动发生吗?
//Show or Hide Comments
$('#showHideComments').live('click', function() {
$('#showHideComments').toggle(function() {
$(".commentsSwitch").animate({"marginLeft": "+=53px"}, 500);
$("#comments").fadeIn(300);
$("#addComment").fadeIn(300);
},function(){
$(".commentsSwitch").animate({"marginLeft": "-=53px"}, 500);
$("#comments").fadeOut(300);
$("#addComment").fadeOut(300);
});
});
谢谢!
最佳答案
您不能同时使用live
和toggle
。你能做的就是简单地制作你自己的“切换”:
$('#showHideComments').live('click', function() {
if($("#addComment").is(':visible')){
$(".commentsSwitch").animate({"marginLeft": "-=53px"}, 500);
$("#comments, #addComment").fadeOut(300);
} else {
$(".commentsSwitch").animate({"marginLeft": "+=53px"}, 500);
$("#comments, #addComment").fadeIn(300);
};
});
live
绑定(bind)到 click
,但是,当调用 toggle
时,它也(通常)在单击时绑定(bind)。您应该决定“生活”是否真的是您所需要的。例如,如果在页面使用过程中通过AJAX替换#showHideComments
对象,那么您需要live和我的解决方案。但是,如果它没有被换出并保持不变,只需使用原始 live
函数的内部(只需切换代码)即可。
关于jquery - 使用带有切换事件的 jQuery .live,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2172614/