disable a hyperlink using jQuery

2019-01-06 12:18发布

<a href="gohere.aspx" class="my-link">Click me</a>

I did

$('.my-link').attr('disabled', true);

but it didn't work

Is there an easy way to disable the hyperlink using jquery? Remove href? I would rather not fiddle with href. So if I can do it w/o removing href, that would be great.

11条回答
相关推荐>>
2楼-- · 2019-01-06 12:36

Removing the href attribute definitely seems to the way to go. If for some reason you need it later, I would just store it in another attribute, e.g.

$(".my-link").each(function() {
    $(this).attr("data-oldhref", $(this).attr("href"));
    $(this).removeAttr("href");
});

This is the only way to do it that will make the link appear disabled as well without writing custom CSS. Just binding a click handler to false will make the link appear like a normal link, but nothing will happen when clicking on it, which may be confusing to users. If you are going to go the click handler route, I would at least also .addClass("link-disabled") and write some CSS that makes links with that class appear like normal text.

查看更多
ゆ 、 Hurt°
3楼-- · 2019-01-06 12:36

The disabled attribute isn't valid on all HTML elements I believe, see the MSDN article. That and the proper value for disabled is simply "disabled". Your best approach is to bind a click function that returns false.

查看更多
\"骚年 ilove
4楼-- · 2019-01-06 12:39

I know it's an old question but it seems unsolved still. Follows my solution...

Simply add this global handler:

$('a').click(function()
{
     return ($(this).attr('disabled')) ? false : true;
});

Here's a quick demo: http://jsbin.com/akihik/3

you can even add a bit of css to give a different style to all the links with the disabled attribute.

e.g

a[disabled]
{
    color: grey; 
}

Anyway it seems that the disabled attribute is not valid for a tags. If you prefer to follow the w3c specs you can easily adopt an html5 compliant data-disabled attribute. In this case you have to modify the previous snippet and use $(this).data('disabled').

查看更多
冷血范
5楼-- · 2019-01-06 12:50

This also works well. Is simple, lite, and doesn't require jQuery to be used.

<a href="javascript:void(0)">Link</a>
查看更多
相关推荐>>
6楼-- · 2019-01-06 12:51

Try:

$(this).prop( "disabled", true );
查看更多
在下西门庆
7楼-- · 2019-01-06 12:53

The pointer-events CSS property is a little lacking when it comes to support (caniuse.com), but it's very succinct:

.my-link { pointer-events: none; } 
查看更多
登录 后发表回答