使用jQuery .live和切换事件

时间:2010-01-31 17:32:52

标签: jquery

我的代码正在运行,但要求我点击两次以激活我的链接(一次用于点击事件,一次用于切换事件。)我该怎么做才能做到这一点我只需要点击一次以便切换会自动发生吗?

    //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 个答案:

答案 0 :(得分:42)

您不能同时使用livetoggle。你可以做的,只是让你自己“切换”各种各样:

$('#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时,它也会在点击时绑定(通常)。你应该决定'live'是否真的是你需要的。例如,如果在使用页面期间通过AJAX替换#showHideComments对象,那么您需要实时和我的解决方案。但是,如果它没有换出并保持不变,只需使用原始live功能的内部(只需切换代码),您就会变得很好。

答案 1 :(得分: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 :(得分: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');
});

答案 3 :(得分:1)

live已弃用。请改用on 例如:

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