JQuery: Disable click event

前端 未结 5 1984
梦如初夏
梦如初夏 2021-01-15 09:56

I want to disable all click events on my page but some of events are still getting called, suppose I have html as below

相关标签:
5条回答
  • 2021-01-15 10:19

    onclick attribute has a higher priority here. You can loop your <a> elements and unset this attribute:

    $('#parent a').each(function () {
      $(this).attr('onclick', '');
    }).click(function () {
      // ...
    });
    
    0 讨论(0)
  • 2021-01-15 10:24

    There is an attribute you should use to make all things disabled.

    var nodes = document.getElementById("parent").getElementsByTagName('*');
    for(var i = 0; i < nodes.length; i++) {
         nodes[i].disabled = true;
    }
    

    Unfortunately disable is not valid with anchor tags.

    There you should use :

    var nodes = document.getElementById("parent").getElementsByTagName('a');
    for(var i = 0; i < nodes.length; i++) {
      nodes[i].onclick = function(e){
        e.preventDefault();
        // YOUR CODES HERE
      }
    }
    

    try to combine these two methods according to your needs

    0 讨论(0)
  • 2021-01-15 10:35

    If you want to disable it for any element under that div you must type:

    $('#parent *').click( function(e)
    {
         e.stopPropagation();
         e.preventDefault();
         e.stopImmediatePropagation();
         return false;
    });
    
    0 讨论(0)
  • 2021-01-15 10:44

    Just remove the onclick attribute from elements that have it, and unbind the 'click' event using .off('click') method

    $('#parent *[onclick]').removeAttr('onclick').off('click');
    
    0 讨论(0)
  • 2021-01-15 10:44

    try this plugin to temporary disable onclick AND jQuery click events:-

    $.fn.disableClick = function (disable){
        this.each(function() {
            if(disable){
                if(this.onclick)
                    $(this).data('onclick', this.onclick).removeAttr('onclick');
                if($._data(this, 'events') && $._data(this, 'events').click)
                    $(this).data('click', $.extend(true, {}, $._data(this, 'events').click)).off('click');
            }
            else{
                if($(this).data('onclick'))
                    this.onclick = $(this).data('onclick');
                if($(this).data('click'))
                    for(var i in $(this).data('click'))
                        $(this).on('click', $(this).data('click')[i].handler);
            }
        });
        return this;
    };
    
    
    //disable clicks
    $('#parent *').disableClick(true);
    
    //enable clicks
    $('#parent *').disableClick(false);
    

    DEMO

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