Using jQuery .live with toggle event

后端 未结 4 698
抹茶落季
抹茶落季 2020-12-01 01:29

My code is working, but requiring me to click twice to active my chaining (once for the click event, and once for the toggle event.) What can I do to make it so I only have

相关标签:
4条回答
  • 2020-12-01 02:03

    live is deprecated. Use on instead For instance:

    $(document).on 'click', 'a[data-object="save-post"]', () ->
      alert 'Saving the post...'
    
    0 讨论(0)
  • 2020-12-01 02:06

    Better yet, use $(this) for the toggle so it refers to the parent - this will work better with multiple instances based on classes or unique objects referred by ID at the parent:

    $('#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');
    });
    
    0 讨论(0)
  • 2020-12-01 02:07
    //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 will also work :)

    0 讨论(0)
  • 2020-12-01 02:15

    You cannot use live and toggle together. What you can do, is simply make your own "toggle" of sorts:

    $('#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 is binding to click, however, when toggle is called, it is also bound (normally) on click. You should decide if 'live' is really what you need. For instance, if #showHideComments object is replaced via AJAX during the use of the page, then you need live and my solution. However, if it isn't swapped out and remains the same, just use the inside of your original live function (just the toggle code) and you will be golden.

    0 讨论(0)
提交回复
热议问题