使用jQuery .live和切换事件
我的代码正在运行,但要求我点击两次以激活我的链接(一次用于点击事件,一次用于切换事件。)我该怎么做才能使我只需点击一次以便切换将自动发生?
//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
绑定到click
,但是,当调用toggle
时,它也会在点击时绑定(通常)。 您应该决定“实时”是否真的符合您的需求。 例如,如果在使用页面期间通过AJAX替换#showHideComments
对象,那么您需要实时和我的解决方案。 但是,如果它没有换出并保持不变,只需使用原始live
function的内部(只需切换代码),您就会变得金色。
//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); }).trigger('click'); });
这也有效:)
更好的是,使用$(this)进行切换,以便它引用父级 – 这将更好地处理基于类或父级ID引用的唯一对象的多个实例:
$('#showHideComments').live('click', function() { $(this).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); }).trigger('click'); });
live
已被弃用。 使用而不是例如:
$(document).on 'click', 'a[data-object="save-post"]', () -> alert 'Saving the post...'