How to remove $(document).on click event?

前端 未结 7 1984
孤独总比滥情好
孤独总比滥情好 2021-01-06 08:13

Here is the code to add event

   $(document).on({
      click: function() {
        $(this).hide();
        $(\'#form_name\').removeClass(\'hide\');
                 


        
相关标签:
7条回答
  • 2021-01-06 08:45

    You need to pass the event to unbind to .off(), also see the use of namepsaced event names

    $(document).on({
        'click.myevent': function () {
            $(this).hide();
            $('#form_name').removeClass('hide');
            $('#form_template_name')
                .attr('placeholder', $(this).text())
                .focus();
        }
    }, '.form-template-name');
    

    and

    $(document).off('click.myevent', '.form-template-name');
    

    Demo: Fiddle

    0 讨论(0)
  • 2021-01-06 08:50

    You can try with:

    var clickEvent = function() {
        $(this).hide();
        $('#form_name').removeClass('hide');
        $('#form_template_name')
          .attr('placeholder', $(this).text())
          .focus();
    };
    
    $(document).on({
       click: clickEvent         
    }, '.form-template-name');
    

    And unbind it with:

    $(document).unbind('click', clickEvent);
    
    0 讨论(0)
  • 2021-01-06 08:52

    Try this.

    $(document).off('click', '.form-template-name');
    
    0 讨论(0)
  • Change your click handler to:

    $(document).on({
        'click.myevent': function () {
            $(this).hide();
            $('#form_name').removeClass('hide');
            $('#form_template_name')
                .attr('placeholder', $(this).text())
                .focus();
        }
    }, '.form-template-name');
    

    then you can use .off(), with name spaced event names:

    $(document).off('click.myevent', '.form-template-name');
    
    0 讨论(0)
  • 2021-01-06 09:01

    You can also try using the event.preventDefault() functionality. It is described in more detail here: http://api.jquery.com/event.preventdefault/

    0 讨论(0)
  • 2021-01-06 09:06

    An event handler is bound to an element. You can unbind an event handler from the element it is attached to, but you can't unbind it from a descendant element since that isn't where it is listening.

    You can either:

    1. Examine the target property of the event object (the first argument to your event handler function) to see what element was clicked on and then return before doing anything.
    2. Bind a new event handler to the elements you want stop the event from triggering from and prevent the event from continuing up the DOM.
    0 讨论(0)
提交回复
热议问题