如何在 Firefox 和 Chrome 中使用 javascript 禁用所有 <a> 链接

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8002579/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 01:57:48  来源:igfitidea点击:

How to disable all <a> links using javascript in Firefox and Chrome

javascriptfirefoxgoogle-chromecross-browser

提问by ran

I want to disable all href links in my page. i am using the below code and it is working fine only in IE.

我想禁用我页面中的所有 href 链接。我正在使用下面的代码,它只能在 IE 中正常工作。

var elems = document.getElementsByTagName("*");
    var len = elems.length;
    for (i=0; i<len; i++) {
           if(elems[i].tagName.toLowerCase() == 'a'){
               elems[i].disabled = true;           
           }
       }

but i want work it on all browsers. can somebody please help me how to overcome this issue.

但我想在所有浏览器上工作。有人可以帮我解决这个问题吗?

Thanks in advance.

提前致谢。

回答by jfriend00

If you don't want to change the href of the links, one could do this too:

如果您不想更改链接的 href,也可以这样做:

window.onload = function() {
    var anchors = document.getElementsByTagName("a");
    for (var i = 0; i < anchors.length; i++) {
        anchors[i].onclick = function() {return false;};
    }
};

Working demo here: http://jsfiddle.net/jfriend00/9YkJQ/.

这里的工作演示:http: //jsfiddle.net/jfriend00/9YkJQ/

回答by David

This is a very old thread but just in case someone else comes to this page, the disabled attribute can be set by using:

这是一个非常古老的线程,但为了防止其他人访问此页面,可以使用以下方法设置 disabled 属性:

element.setAttribute('disabled', 'disabled');

This is recognized in all browsers and will disable the link. However, firing events on a disabled link is handled differently in different browsers & versions. FF & Chrome will still fire the onclick event where IE8+, not in compatibility mode, will not fire events. This is not necessary if there is no onclick event handler wired to the anchor, a normal href will not fire once the disabled attribute has been set. To stop the firing of the click event, the above code would work. The parens are not required and personally, I don't use them in this case as I assume parens are for grouping or for a function. Seems unnecessary in the solution provided before.

这在所有浏览器中都会被识别,并将禁用该链接。但是,在不同的浏览器和版本中,对禁用链接的触发事件的处理方式不同。FF 和 Chrome 仍会触发 onclick 事件,而 IE8+(非兼容模式)不会触发事件。如果没有连接到锚点的 onclick 事件处理程序,则这不是必需的,一旦设置了 disabled 属性,就不会触发正常的 href 。要停止触发点击事件,上面的代码将起作用。括号不是必需的,我个人在这种情况下不使用它们,因为我假设括号用于分组或函数。在之前提供的解决方案中似乎没有必要。