使用jQuery的.live与toggle事件

20
我的代码可以工作,但需要我点击两次才能激活我的链式操作(一次是点击事件,一次是切换事件)。我该怎么做才能只需要单击一次,以便切换自动发生?
    //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);
    });
});

感谢!

4个回答

42

你不能同时使用livetoggle。你可以做的是,简单地创建自己的"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 时,它也会被 (通常) 绑定在 click 上。你需要决定是否真正需要使用 'live'。例如,如果在页面使用期间通过 AJAX 替换了 #showHideComments 对象,则需要使用 live 和我的解决方案。但是,如果它没有被替换并且保持不变,请只使用原始 live 函数中的代码 (仅切换代码),然后你就可以了。


3
嘘,还可以结合选择器! - Nick Craver
谢谢!正是我需要的。我确实需要使用live,因为数据是通过我的php脚本通过ajax返回的。谢谢你的优化建议,我还在学习中 :) - Dave Kiss

4
//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');
});

这也能正常工作 :)

2
更好的做法是使用 $(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');
});

2

live已经过时了,应该使用on代替。 例如:

$(document).on 'click', 'a[data-object="save-post"]', () ->
  alert 'Saving the post...'

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接