2010-01-31 37 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...'