How to enable or disable an anchor using jQuery?

2019-01-01 10:53发布

How to enable or disable an anchor using jQuery?

16条回答
君临天下
2楼-- · 2019-01-01 11:14

So with a combination of the responses above, I came up with this.

a.disabled { color: #555555; cursor: default; text-decoration: none; }

$(".yourClass").addClass("disabled").click(function(e){ e.preventDefault(); 
查看更多
墨雨无痕
3楼-- · 2019-01-01 11:15

For situations where you must put text or html content within an anchor tag, but you simply don't want any action to be taken at all when that element is clicked (like when you want a paginator link to be in the disabled state because it's the current page), simply cut out the href. ;)

<a>3 (current page, I'm totally disabled!)</a>

The answer by @michael-meadows tipped me off to this, but his was still addressing scenarios where you still have to / are working with jQuery/JS. In this case, if you have control over writing the html itself, simply x-ing the href tag is all you need to do, so the solution is a pure HTML one!

Other solutions without jQuery finagling which keep the href require you to put a # in the href, but that causes the page to bounce to the top, and you just want it to be plain old disabled. Or leaving it empty, but depending on browser, that still does stuff like jump to the top, and, it is invalid HTML according to the IDEs. But apparently an a tag is totally valid HTML without an HREF.

Lastly, you might say: Okay, why not just dump the a tag altogether than? Because often you can't, the a tag is used for styling purposes in the CSS framework or control you're using, like Bootstrap's paginator:

http://twitter.github.io/bootstrap/components.html#pagination

查看更多
伤终究还是伤i
4楼-- · 2019-01-01 11:17

If you are trying to block all interaction with the page you might want to look at the jQuery BlockUI Plugin

查看更多
梦该遗忘
5楼-- · 2019-01-01 11:19
$("a").click(function(){
                alert('disabled');
                return false;

}); 
查看更多
登录 后发表回答