结合使用jQuery .live和toggle事件 [英] Using jQuery .live with toggle event
问题描述
我的代码可以正常工作,但是要求我单击两次以激活链接(单击事件一次,而切换事件一次.)我可以做些什么,因此只需单击一次即可切换会自动发生吗?
My code is working, but requiring me to click twice to active my chaining (once for the click event, and once for the toggle event.) What can I do to make it so I only have to click once so that the toggle will automatically occur?
//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
.您可以做的只是简单地进行自己的切换":
You cannot use live
and toggle
together. What you can do, is simply make your own "toggle" of sorts:
$('#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
绑定到click
,但是,当调用toggle
时,单击时也绑定(通常).您应该确定生活"是否真的是您所需要的.例如,如果在使用页面期间通过AJAX替换了#showHideComments
对象,那么您需要实时的解决方案.但是,如果它没有被换出并保持不变,则只需使用原始live
函数的内部(仅切换代码),您就会大吃一惊.
live
is binding to click
, however, when toggle
is called, it is also bound (normally) on click. You should decide if 'live' is really what you need. For instance, if #showHideComments
object is replaced via AJAX during the use of the page, then you need live and my solution. However, if it isn't swapped out and remains the same, just use the inside of your original live
function (just the toggle code) and you will be golden.
这篇关于结合使用jQuery .live和toggle事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!