2010-01-31 34 views
20

我的代码正在工作,但需要点击两次来激活我的链接(一次用于点击事件,一次用于切换事件)。我该怎么做才能让它变成只有我必须点击一次,以便切换会自动发生?使用带切换事件的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); 
    }); 
}); 

谢谢!

回答

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被调用,它也必然(常)上点击。你应该决定'生活'是否真的是你需要的。例如,如果#showHideComments对象在使用页面期间通过AJAX替换,则需要实时和我的解决方案。但是,如果它未被换出并保持不变,只需使用原始live函数的内部(只是切换代码)即可,您将成为金手指。

+3

Pssst,结合选择呢! – 2010-01-31 17:39:52

+0

@尼克,很棒的一点。更新。谢谢! – 2010-01-31 17:43:17

+0

谢谢!正是我需要的。我确实需要使用live,因为数据是通过我的php脚本通过ajax返回的。感谢您的优化,我仍然在学习:) – 2010-01-31 17:49:29

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

更重要的是,使用$(本)为翻转,因此指父 - 这将更好地工作,根据由被称为类或唯一对象多个实例在父代的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'); 
}); 
1

live已弃用。使用on代替 例如:

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