Disable and Enable ALL Hyperlinks using JQuery

2020-06-17 06:18发布

I have the below which disables all hyperlinks but after an event I want to enable them back all again, how can I do this?

$("a").click(function() { return false; });

I don't think its as simple as just setting it to true. ;)

Thanks all

10条回答
成全新的幸福
2楼-- · 2020-06-17 06:36
var disableLink = function(){ return false;};
$('a').bind('click', disableLink);

to restore:

$('a').unbind('click', dsiableLink);
查看更多
Fickle 薄情
3楼-- · 2020-06-17 06:38

Instead of binding your "click" handler that way, do this:

$('a').bind("click.myDisable", function() { return false; });

Then when you want to remove that handler it's easy:

$('a').unbind("click.myDisable");

That way you avoid messing up other stuff that might be bound to "click". If you just unbind "click", you unbind everything bound to that event.

edit in 2014 — the way you bind events now is with .on():

$('a').on('click.myDisable', function() { return false; });

Probably it'd be better to do this:

$('a').on('click.myDisable', function(e) { e.preventDefault(); });

To unbind:

$('a').off('click.myDisable');

Finally, you could bind a handler to the document body and deal with <a> tags that are dynamically added:

$('body').on('click.myDisable', 'a', function(e) { e.preventDefault(); });

// to unbind

$('body').off('click.myDisable');
查看更多
smile是对你的礼貌
4楼-- · 2020-06-17 06:38

Or even better, simply toggle the display of a large element with the high z-index. In the example below, the div covers the body.

var link = document.getElementsByTagName('a')[2];
var noclick = document.getElementById('noclick');

link.onclick = function() {
  noclick.className = 'on';
}
#noclick {
  display: none;
  position: absolute;
  left: 0px;
  right: 0px;
  top: 0px;
  bottom: 0px;
  /* Make sure this floats over content */
  z-index: 100; 
}

#noclick.on {
  display: block;
}
<body>
  <div id="noclick"></div>
  <a href="#">one</a>
  <a href="#">two</a>
  <a href="#">three</a>
</body>

查看更多
Ridiculous、
5楼-- · 2020-06-17 06:39

You want to unbind the event: http://api.jquery.com/unbind/

查看更多
Emotional °昔
6楼-- · 2020-06-17 06:42
$(function(){


    $.myStopAnchor = function(){
      $stop = true;
    }

    $.myNoStopAnchor = function(){
      $stop = false;
    }

    $.myNoStopAnchor();

    $("a").click(function(ev) { 
       if ($stop){
         ev.stopPropagation()
       }
       return !$stop; 
    });

});
查看更多
Juvenile、少年°
7楼-- · 2020-06-17 06:45

You should be able to unbind it.

$("a").unbind("click");
查看更多
登录 后发表回答