如何禁用JavaScript中的href链接?

时间:2022-08-10 15:00:35

I have a tag <a href="#"> Previous </a> 1 2 3 4 <a href="#"> Next </a> and in some conditions I want this tag to be completely disabled.

我有一个标签之前的, 1 2 3 4 Next ,在某些情况下,我希望这个标签完全禁用。

Code from comments (this is how the link is generated)

来自注释的代码(这是链接生成的方式)

if (n_index != n_pages) 
    a = a+'<li><a href="#" onclick="javascript:paginateAjaxPage('+(n_index+1) +','+stype+');">></a></li><li><a href="#" onclick="javascript:paginateAjaxPage('+n_pages+','+stype+');" >>></a></li>'; 
else 
    a = a+'<li><a style="cursor: pointer;" onclick="return false;">></a></li><li><a style="cursor: pointer;" onclick="return false" >>></a></li>'; 
a = a+'</ul></div>';

19 个解决方案

#1


144  

Try this when you dont want user to redirect on click

当您不希望用户重定向时,请尝试此方法。

<a href="javascript: void(0)">I am a useless link</a>

#2


60  

you can deactivate all links in a page with this style class:

您可以在页面中禁用此样式类的所有链接:

a {
    pointer-events:none;
}

now of course the trick is deactivate the links only when you need to, this is how to do it:

当然,诀窍是在你需要的时候才去激活链接,这是怎么做的:

use an empty A class, like this:

使用一个空的类,像这样:

a {}

then when you want to deactivate the links, do this:

然后,当你想要停用链接时,可以这样做:

    GetStyleClass('a').pointerEvents = "none"

    function GetStyleClass(className)
    {
       for (var i=0; i< document.styleSheets.length; i++) {
          var styleSheet = document.styleSheets[i]

          var rules = styleSheet.cssRules || styleSheet.rules

          for (var j=0; j<rules.length; j++) {
             var rule = rules[j]

             if (rule.selectorText === className) {
                return(rule.style)
             }
          }
       }

       return 0
    }

NOTE: CSS rule names are transformed to lower case in some browsers, and this code is case sensitive, so better use lower case class names for this

注意:在某些浏览器中,CSS规则名称被转换为小写字母,这段代码是区分大小写的,因此最好使用小写类名。

to reactivate links:

重新激活链接:

GetStyleClass('a').pointerEvents = ""

check this page http://caniuse.com/pointer-events for information about browser compatibility

请查看此页面http://caniuse.com/pointerevents以获得有关浏览器兼容性的信息。

i think this is the best way to do it, but sadly IE, like always, will not allow it :) i'm posting this anyway, because i think this contains information that can be useful, and because some projects use a know browser, like when you are using web views on mobile devices.

我认为这是最好的方法,但不幸的是,像永远,不会允许它:)我发布这个,因为我认为它包含的信息可能是有用的,因为一些项目使用知道浏览器,比如当你在移动设备上使用web视图。

if you just want to deactivate ONE link (i only realize THAT was the question), i would use a function that manualy sets the url of the current page, or not, based on that condition. (like the solution you accepted)

如果您只是想要停用一个链接(我只知道这是一个问题),那么我将使用一个功能,该函数将根据该条件设置当前页面的url。(就像你接受的解决方案一样)

this question was a LOT easier than i thought :)

这个问题比我想象的要容易得多。

#3


15  

You can simply give it an empty hash:

你可以简单地给它一个空的散列:

anchor.href = "#";

or if that's not good enough of a "disable", use an event handler:

或者如果这还不够“禁用”,请使用事件处理程序:

anchor.href = "javascript:void(0)";

#4


7  

Try this using jQuery:

使用jQuery试试这个:

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

#5


6  

anchor.href = null;

#6


4  

The easiest way to disable a link is simply not to show it. Run this function whenever you want to test if your condition is met to hide the Previous button (replace if (true) with your condition):

禁用链接的最简单方法就是不显示它。当您想要测试您的条件是否被满足来隐藏之前的按钮时,运行这个函数(如果您的条件是正确的):

var testHideNav = function() {
    var aTags = document.getElementsByTagName('a'),
        atl = aTags.length,
        i;

    for (i = 0; i < atl; i++) {
        if (aTags[i].innerText == "Previous") {
            if (true) { // your condition to disable previous
                aTags[i].style.visibility = "hidden";
            } else {
                aTags[i].style.visibility = "visible";
            }
        } else if (aTags[i].innerText == "Next") {
            if (false) { // your condition to disable next
                aTags[i].style.visibility = "hidden";
            } else {
                aTags[i].style.visibility = "visible";
            }
        }
    }
};

Then run testHideNav() whenever you need to make the check if your condition has changed.

然后运行testHideNav(),当您需要进行检查时,如果您的条件已经改变。

#7


4  

(function ($) {
    $( window ).load(function() {
        $('.navbar a').unbind('click');
        $('.navbar a').click(function () {
            //DO SOMETHING
            return false;
        });
    });
})(jQuery);

I find this way easier to implement. And it has the advantage that you js. Is not inside your html but in a different file. I think that without the unbind. Both events are still active. Not sure. But in a way you only need this one event

我发现这样更容易实现。而且它有你js的优势。不是在html中,而是在另一个文件中。我认为没有了解脱。这两个事件仍然是活跃的。不确定。但在某种程度上,你只需要这个事件。

#8


3  

Use a span and a javascript onclick instead. Some browsers "jump" if you have a link and "#" href.

使用一个span和一个javascript onclick代替。如果你有一个链接和“#”href,一些浏览器会“跳转”。

#9


3  

This is possible, too:

这是可能的:

<a href="javascript:void(0)" onclick="myfunction()">

Link doesn't go anywhere by your function will be executed.

链接不会被你的函数执行。

#10


2  

So the above solutions make the link not work, but don't make it visible (AFAICT) that the link is no longer valid. I've got a situation where I've got a series of pages and want to disable (and make it obvious that it's disabled) the link that points to the current page.

因此,以上的解决方案使链接不起作用,但是不要让它可见(AFAICT),链接不再有效。我有一种情况,我有一系列的页面,想要禁用(并使它明显的是禁用的)指向当前页面的链接。

So:

所以:

window.onload = function() {
    var topics = document.getElementsByClassName("topics");
    for (var i = topics.length-1; i > -1; i-- ) {
        for (var j = topics[i].childNodes.length-1; j > -1; j--) {
             if (topics[i].childNodes[j].nodeType == 1) {
                if (topics[i].childNodes[j].firstChild.attributes[0].nodeValue == this.n_root3) {
                    topics[i].childNodes[j].innerHTML = topics[i].childNodes[j].firstChild.innerHTML;
                }
            }
        }
    }
}

This walks through the list of links, finds the one that points to the current page (the n_root3 might be a local thing, but I imagine document must have something similar), and replaces the link with the link text contents.

这将遍历链接列表,找到指向当前页面的链接(n_root3可能是本地内容,但我想文档必须有类似的内容),并替换链接文本内容的链接。

HTH

HTH

#11


2  

I had a similar need, but my motivation was to prevent the link from being double-clicked. I accomplished it using jQuery:

我也有类似的需求,但我的动机是阻止链接被双击。我使用jQuery完成了它:

$(document).ready(function() {
    $("#myLink").on('click', doSubmit);
});

var doSubmit = function() {
    $("#myLink").off('click');
    // do things here
};

The HTML looks like this:

HTML是这样的:

<a href='javascript: void(0);' id="myLink">click here</a>

#12


2  

MDN recommends element.removeAttribute(attrName); over setting the attribute to null (or some other value) when you want to disable it. In this case it would be element.removeAttribute("href");

MDN建议element.removeAttribute(attrName);当您想要禁用它时,将属性设置为null(或其他值)。在本例中,它将是element.removeAttribute(“href”);

https://developer.mozilla.org/en-US/docs/Web/API/Element/removeAttribute

https://developer.mozilla.org/en-US/docs/Web/API/Element/removeAttribute

#13


0  

Install this plugin for jquery and use it

为jquery安装这个插件并使用它。

http://plugins.jquery.com/project/jqueryenabledisable

http://plugins.jquery.com/project/jqueryenabledisable

It allows you to disable/enable pretty much any field in the page.

它允许您禁用/启用页面中的任何字段。

If you want to open a page on some condition write a java script function and call it from href. If the condition satisfied you open page otherwise just do nothing.

如果您想在某些条件下打开一个页面,请编写一个java脚本函数并从href调用它。如果条件满足你打开页面,否则什么也不做。

code looks like this:

代码是这样的:

<a href="javascript: openPage()" >Click here</a>

and function:
function openPage()
{
if(some conditon)
opener.document.location = "http://www.google.com";
}
}

You can also put the link in a div and set the display property of the Style attribute to none. this will hide the div. For eg.,

您还可以将链接放在div中,并将Style属性的显示属性设置为none。这将隐藏div。

<div id="divid" style="display:none">
<a href="Hiding Link" />
</div>

This will hide the link. Use a button or an image to make this div visible now by calling this function in onclick as:

这将隐藏链接。使用按钮或图像使这个div现在可见,在onclick中调用此函数为:

<a href="Visible Link" onclick="showDiv()">

and write the js code as:

function showDiv(){
document.getElememtById("divid").style.display="block";
}

You can also put an id tag to the html tag, so it would be

您还可以将id标记放到html标记中,这样就可以了。

<a id="myATag" href="whatever"></a>

And get this id on your javascript by using

通过使用javascript来获取这个id。

document.getElementById("myATag").value="#"; 

One of this must work for sure haha

其中一个肯定是肯定的,哈哈。

#14


0  

Thank you All...

谢谢大家……

My issue solved by below code:

我的问题通过以下代码解决:

<a href="javascript:void(0)"> >>> </a>

#15


0  

Another method to disable link

另一种禁用链接的方法。

element.removeAttribute('href');

anchor tag without href would react as disabled/plain text

没有href的锚标记将作为禁用/纯文本。

<a> w/o href </a>

instead of <a href="#"> with href </a>

而不是和href

see jsFiddel

看到jsFiddel

hope this is heplful.

希望这是heplful。

#16


0  

Instead of void you can also use:

你也可以用:

<a href="javascript:;">this link is disabled</a> 

#17


0  

This is how I disable in on click

这就是我如何禁用点击。

$('.one-click').on("click", function (e) {
   $( this ).addClass('disabled');
});

where .disabled class coming form bootstrap.

在这里。禁用的类来自引导程序。

Qupte form bootstrap site (here)

Qupte表单引导站点(这里)

Link functionality caveat

链接功能说明

The .disabled class uses pointer-events: none to try to disable the link functionality of s, but that CSS property is not yet standardized. In addition, even in browsers that do support pointer-events: none, keyboard navigation remains unaffected, meaning that sighted keyboard users and users of assistive technologies will still be able to activate these links. So to be safe, add a tabindex="-1" attribute on these links (to prevent them from receiving keyboard focus) and use custom JavaScript to disable their functionality.

残障类使用pointerevents: none试图禁用s的链接功能,但CSS属性尚未标准化。此外,即使在支持pointerevents的浏览器中,键盘导航仍然不受影响,这意味着有视力的键盘用户和辅助技术的用户仍然能够激活这些链接。为了安全起见,在这些链接上添加tabindex="-1"属性(以防止它们接收键盘焦点),并使用定制的JavaScript来禁用它们的功能。

#18


0  

I was looking for something simple, so I combined the above answers (suggesting this: javascript: void(0);) into a JQuery .attr(), like so:

我在寻找一些简单的东西,所以我将上面的答案结合在一起(建议:javascript: void(0);)到JQuery .attr(),比如:

$("a").attr("href", "javascript: void(0);" ); 

#19


-4  

Below code for disabled links:

以下是禁用链接的代码:

<a href="javascript: void(0)">test disabled link</a> 

another very simple solution is:

另一个很简单的解决办法是:

<a href="#">test disabled link</a>

First solution is efficient.

第一个解决方案是有效的。

#1


144  

Try this when you dont want user to redirect on click

当您不希望用户重定向时,请尝试此方法。

<a href="javascript: void(0)">I am a useless link</a>

#2


60  

you can deactivate all links in a page with this style class:

您可以在页面中禁用此样式类的所有链接:

a {
    pointer-events:none;
}

now of course the trick is deactivate the links only when you need to, this is how to do it:

当然,诀窍是在你需要的时候才去激活链接,这是怎么做的:

use an empty A class, like this:

使用一个空的类,像这样:

a {}

then when you want to deactivate the links, do this:

然后,当你想要停用链接时,可以这样做:

    GetStyleClass('a').pointerEvents = "none"

    function GetStyleClass(className)
    {
       for (var i=0; i< document.styleSheets.length; i++) {
          var styleSheet = document.styleSheets[i]

          var rules = styleSheet.cssRules || styleSheet.rules

          for (var j=0; j<rules.length; j++) {
             var rule = rules[j]

             if (rule.selectorText === className) {
                return(rule.style)
             }
          }
       }

       return 0
    }

NOTE: CSS rule names are transformed to lower case in some browsers, and this code is case sensitive, so better use lower case class names for this

注意:在某些浏览器中,CSS规则名称被转换为小写字母,这段代码是区分大小写的,因此最好使用小写类名。

to reactivate links:

重新激活链接:

GetStyleClass('a').pointerEvents = ""

check this page http://caniuse.com/pointer-events for information about browser compatibility

请查看此页面http://caniuse.com/pointerevents以获得有关浏览器兼容性的信息。

i think this is the best way to do it, but sadly IE, like always, will not allow it :) i'm posting this anyway, because i think this contains information that can be useful, and because some projects use a know browser, like when you are using web views on mobile devices.

我认为这是最好的方法,但不幸的是,像永远,不会允许它:)我发布这个,因为我认为它包含的信息可能是有用的,因为一些项目使用知道浏览器,比如当你在移动设备上使用web视图。

if you just want to deactivate ONE link (i only realize THAT was the question), i would use a function that manualy sets the url of the current page, or not, based on that condition. (like the solution you accepted)

如果您只是想要停用一个链接(我只知道这是一个问题),那么我将使用一个功能,该函数将根据该条件设置当前页面的url。(就像你接受的解决方案一样)

this question was a LOT easier than i thought :)

这个问题比我想象的要容易得多。

#3


15  

You can simply give it an empty hash:

你可以简单地给它一个空的散列:

anchor.href = "#";

or if that's not good enough of a "disable", use an event handler:

或者如果这还不够“禁用”,请使用事件处理程序:

anchor.href = "javascript:void(0)";

#4


7  

Try this using jQuery:

使用jQuery试试这个:

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

#5


6  

anchor.href = null;

#6


4  

The easiest way to disable a link is simply not to show it. Run this function whenever you want to test if your condition is met to hide the Previous button (replace if (true) with your condition):

禁用链接的最简单方法就是不显示它。当您想要测试您的条件是否被满足来隐藏之前的按钮时,运行这个函数(如果您的条件是正确的):

var testHideNav = function() {
    var aTags = document.getElementsByTagName('a'),
        atl = aTags.length,
        i;

    for (i = 0; i < atl; i++) {
        if (aTags[i].innerText == "Previous") {
            if (true) { // your condition to disable previous
                aTags[i].style.visibility = "hidden";
            } else {
                aTags[i].style.visibility = "visible";
            }
        } else if (aTags[i].innerText == "Next") {
            if (false) { // your condition to disable next
                aTags[i].style.visibility = "hidden";
            } else {
                aTags[i].style.visibility = "visible";
            }
        }
    }
};

Then run testHideNav() whenever you need to make the check if your condition has changed.

然后运行testHideNav(),当您需要进行检查时,如果您的条件已经改变。

#7


4  

(function ($) {
    $( window ).load(function() {
        $('.navbar a').unbind('click');
        $('.navbar a').click(function () {
            //DO SOMETHING
            return false;
        });
    });
})(jQuery);

I find this way easier to implement. And it has the advantage that you js. Is not inside your html but in a different file. I think that without the unbind. Both events are still active. Not sure. But in a way you only need this one event

我发现这样更容易实现。而且它有你js的优势。不是在html中,而是在另一个文件中。我认为没有了解脱。这两个事件仍然是活跃的。不确定。但在某种程度上,你只需要这个事件。

#8


3  

Use a span and a javascript onclick instead. Some browsers "jump" if you have a link and "#" href.

使用一个span和一个javascript onclick代替。如果你有一个链接和“#”href,一些浏览器会“跳转”。

#9


3  

This is possible, too:

这是可能的:

<a href="javascript:void(0)" onclick="myfunction()">

Link doesn't go anywhere by your function will be executed.

链接不会被你的函数执行。

#10


2  

So the above solutions make the link not work, but don't make it visible (AFAICT) that the link is no longer valid. I've got a situation where I've got a series of pages and want to disable (and make it obvious that it's disabled) the link that points to the current page.

因此,以上的解决方案使链接不起作用,但是不要让它可见(AFAICT),链接不再有效。我有一种情况,我有一系列的页面,想要禁用(并使它明显的是禁用的)指向当前页面的链接。

So:

所以:

window.onload = function() {
    var topics = document.getElementsByClassName("topics");
    for (var i = topics.length-1; i > -1; i-- ) {
        for (var j = topics[i].childNodes.length-1; j > -1; j--) {
             if (topics[i].childNodes[j].nodeType == 1) {
                if (topics[i].childNodes[j].firstChild.attributes[0].nodeValue == this.n_root3) {
                    topics[i].childNodes[j].innerHTML = topics[i].childNodes[j].firstChild.innerHTML;
                }
            }
        }
    }
}

This walks through the list of links, finds the one that points to the current page (the n_root3 might be a local thing, but I imagine document must have something similar), and replaces the link with the link text contents.

这将遍历链接列表,找到指向当前页面的链接(n_root3可能是本地内容,但我想文档必须有类似的内容),并替换链接文本内容的链接。

HTH

HTH

#11


2  

I had a similar need, but my motivation was to prevent the link from being double-clicked. I accomplished it using jQuery:

我也有类似的需求,但我的动机是阻止链接被双击。我使用jQuery完成了它:

$(document).ready(function() {
    $("#myLink").on('click', doSubmit);
});

var doSubmit = function() {
    $("#myLink").off('click');
    // do things here
};

The HTML looks like this:

HTML是这样的:

<a href='javascript: void(0);' id="myLink">click here</a>

#12


2  

MDN recommends element.removeAttribute(attrName); over setting the attribute to null (or some other value) when you want to disable it. In this case it would be element.removeAttribute("href");

MDN建议element.removeAttribute(attrName);当您想要禁用它时,将属性设置为null(或其他值)。在本例中,它将是element.removeAttribute(“href”);

https://developer.mozilla.org/en-US/docs/Web/API/Element/removeAttribute

https://developer.mozilla.org/en-US/docs/Web/API/Element/removeAttribute

#13


0  

Install this plugin for jquery and use it

为jquery安装这个插件并使用它。

http://plugins.jquery.com/project/jqueryenabledisable

http://plugins.jquery.com/project/jqueryenabledisable

It allows you to disable/enable pretty much any field in the page.

它允许您禁用/启用页面中的任何字段。

If you want to open a page on some condition write a java script function and call it from href. If the condition satisfied you open page otherwise just do nothing.

如果您想在某些条件下打开一个页面,请编写一个java脚本函数并从href调用它。如果条件满足你打开页面,否则什么也不做。

code looks like this:

代码是这样的:

<a href="javascript: openPage()" >Click here</a>

and function:
function openPage()
{
if(some conditon)
opener.document.location = "http://www.google.com";
}
}

You can also put the link in a div and set the display property of the Style attribute to none. this will hide the div. For eg.,

您还可以将链接放在div中,并将Style属性的显示属性设置为none。这将隐藏div。

<div id="divid" style="display:none">
<a href="Hiding Link" />
</div>

This will hide the link. Use a button or an image to make this div visible now by calling this function in onclick as:

这将隐藏链接。使用按钮或图像使这个div现在可见,在onclick中调用此函数为:

<a href="Visible Link" onclick="showDiv()">

and write the js code as:

function showDiv(){
document.getElememtById("divid").style.display="block";
}

You can also put an id tag to the html tag, so it would be

您还可以将id标记放到html标记中,这样就可以了。

<a id="myATag" href="whatever"></a>

And get this id on your javascript by using

通过使用javascript来获取这个id。

document.getElementById("myATag").value="#"; 

One of this must work for sure haha

其中一个肯定是肯定的,哈哈。

#14


0  

Thank you All...

谢谢大家……

My issue solved by below code:

我的问题通过以下代码解决:

<a href="javascript:void(0)"> >>> </a>

#15


0  

Another method to disable link

另一种禁用链接的方法。

element.removeAttribute('href');

anchor tag without href would react as disabled/plain text

没有href的锚标记将作为禁用/纯文本。

<a> w/o href </a>

instead of <a href="#"> with href </a>

而不是和href

see jsFiddel

看到jsFiddel

hope this is heplful.

希望这是heplful。

#16


0  

Instead of void you can also use:

你也可以用:

<a href="javascript:;">this link is disabled</a> 

#17


0  

This is how I disable in on click

这就是我如何禁用点击。

$('.one-click').on("click", function (e) {
   $( this ).addClass('disabled');
});

where .disabled class coming form bootstrap.

在这里。禁用的类来自引导程序。

Qupte form bootstrap site (here)

Qupte表单引导站点(这里)

Link functionality caveat

链接功能说明

The .disabled class uses pointer-events: none to try to disable the link functionality of s, but that CSS property is not yet standardized. In addition, even in browsers that do support pointer-events: none, keyboard navigation remains unaffected, meaning that sighted keyboard users and users of assistive technologies will still be able to activate these links. So to be safe, add a tabindex="-1" attribute on these links (to prevent them from receiving keyboard focus) and use custom JavaScript to disable their functionality.

残障类使用pointerevents: none试图禁用s的链接功能,但CSS属性尚未标准化。此外,即使在支持pointerevents的浏览器中,键盘导航仍然不受影响,这意味着有视力的键盘用户和辅助技术的用户仍然能够激活这些链接。为了安全起见,在这些链接上添加tabindex="-1"属性(以防止它们接收键盘焦点),并使用定制的JavaScript来禁用它们的功能。

#18


0  

I was looking for something simple, so I combined the above answers (suggesting this: javascript: void(0);) into a JQuery .attr(), like so:

我在寻找一些简单的东西,所以我将上面的答案结合在一起(建议:javascript: void(0);)到JQuery .attr(),比如:

$("a").attr("href", "javascript: void(0);" ); 

#19


-4  

Below code for disabled links:

以下是禁用链接的代码:

<a href="javascript: void(0)">test disabled link</a> 

another very simple solution is:

另一个很简单的解决办法是:

<a href="#">test disabled link</a>

First solution is efficient.

第一个解决方案是有效的。