简体   繁体   English

如何禁用 JavaScript 中的 href 链接?

[英]How do I disable a href link in JavaScript?

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.我有一个标签<a href="#"> Previous </a> 1 2 3 4 <a href="#"> Next </a>并且在某些情况下我希望这个标签被完全禁用。

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>';

当您不希望用户在点击时重定向时试试这个

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

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 类,如下所示:

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/pointer-events有关浏览器兼容性的信息

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.我认为这是最好的方法,但遗憾的是 IE 和往常一样,不会允许它:) 无论如何我都会发布这个,因为我认为这包含可能有用的信息,并且因为有些项目使用已知的浏览器,就像您在移动设备上使用 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.如果您只想停用一个链接(我只意识到这是问题所在),我会使用一个函数,根据该条件手动设置或不设置当前页面的 url。 (like the solution you accepted) (就像你接受的解决方案)

this question was a LOT easier than i thought :)这个问题比我想象的要容易得多:)

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)";

Try this using jQuery:使用 jQuery 试试这个:

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

MDN recommends element.removeAttribute(attrName); MDN 推荐element.removeAttribute(attrName); over setting the attribute to null (or some other value) when you want to disable it.当您想要禁用它时,将属性设置为 null(或某个其他值)。 In this case it would be element.removeAttribute("href");在这种情况下,它将是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

anchor.href = null;
\n

(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.它的优势在于你 js。 Is not inside your html but in a different file.不在您的 html 中,而是在不同的文件中。 I think that without the unbind.我认为没有解除绑定。 Both events are still active.这两个事件仍然活跃。 Not sure.没有把握。 But in a way you only need this one event但在某种程度上你只需要这个一个事件

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):每当您想测试是否满足您的条件以隐藏上一个按钮时运行此函数(将if (true)替换为您的条件):

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()

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>

Use a span and a javascript onclick instead.改用跨度和 javascript onclick。 Some browsers "jump" if you have a link and "#" href.如果您有链接和“#”href,某些浏览器会“跳转”。

This is possible, too:这也是可能的:

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

Link doesn't go anywhere by your function will be executed.链接不会去任何地方,您的函数将被执行。

So the above solutions make the link not work, but don't make it visible (AFAICT) that the link is no longer valid.因此,上述解决方案使链接不起作用,但不要使其可见(AFAICT)链接不再有效。 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.我遇到了一种情况,我有一系列页面并且想要禁用(并明确表示它已禁用)指向当前页面的链接。

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 可能是本地的,但我想document必须有类似的东西),并用链接文本内容替换链接。

HTH HTH

Thank you All...谢谢你们...

My issue solved by below code:我的问题通过以下代码解决:

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

Based on many answers and my experience here my best solution:根据许多答案和我的经验,我的最佳解决方案是:

<a href="javascript:">I am a useless link</a>

Some options and theirs caveats :一些选项和他们的警告

<a href="#">I will make you page jump to top</a> 

<a href="#" onclick="DoSomething(); return false;">I'll break others scripts events</a>

<a href="javascript: openPage()" >Please... I should be an onclick event...</a>

<a href="javascript:" onclick="openPage()" >Please...do I even need to be an anchor?</a>

<script>element.removeAttribute("href") // some browsers will remove link style</script>

<script>element.href = null // some browsers will remove link style</script>

<style>
 a.my-off-class {
    pointer-events: none
 }
 /** I disable hover event too. And... Is this a style responsability?
</style>

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>而不是<a href="#"> with href </a>

see jsFiddeljsFiddel

hope this is heplful.希望这是heplful。

除了 void 您还可以使用:

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

0) you better remember that Some browsers "jump" if you have a link and "#" href. 0)你最好记住,如果你有一个链接和“#”href,一些浏览器会“跳转”。 So the best way would be a custom JavaScript所以最好的方法是自定义 JavaScript

1) If you after the custom JavaScript , here it is: 1)如果你在自定义 JavaScript 之后,这里是:

<a href="#" onclick="DoSomething(); return false;">Link</a>

The "return false" prevents the link from actually being followed. “返回假”阻止实际跟踪链接。

2) You may consider avoid using following 2)您可以考虑避免使用以下内容

<a href="javascript:void(0);" onclick="DoSomething();">Link</a>

or或者

  <a href="javascript:;" onclick="DoSomething();">Link</a>

Because the javascript pseudo-protocol can put the page into a waiting state in some browsers, which can have unexpected consequences.因为javascript伪协议可以在某些浏览器中将页面置于等待状态,这可能会产生意想不到的后果。 IE6 is known for it. IE6 是众所周知的。 But If you don't care about IE6, and you are testing everything - it may be a good solution.但是如果您不关心 IE6,并且您正在测试一切 - 这可能是一个很好的解决方案。

3) If you already have jQuery and bootstrap in your project, you can look into using them like so: 3)如果你的项目中已经有jQuerybootstrap ,你可以像这样考虑使用它们:

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

where .disabled class coming form bootstrap.其中.disabled类来自引导程序。

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. .disabled 类使用pointer-events: none尝试禁用 s 的链接功能,但该 CSS 属性尚未标准化。 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.所以为了安全起见,在这些链接上添加一个tabindex="-1"属性(以防止它们接收键盘焦点)并使用custom JavaScript来禁用它们的功能。

and the custom JavaScript was shown in section 1 custom JavaScript显示在第1部分

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.如果您想在某些条件下打开一个页面,请编写一个 java 脚本函数并从 href 调用它。 If the condition satisfied you open page otherwise just do nothing.如果条件满足你打开页面否则什么都不做。

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.您还可以将链接放在 div 中,并将 Style 属性的 display 属性设置为 none。 this will hide the div.这将隐藏 div。 For eg.,例如,

<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:通过在 onclick 中调用此函数,使用按钮或图像使此 div 现在可见:

<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你也可以在 html 标签上放一个 id 标签,这样就可以了

<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其中之一肯定有效哈哈

Use all three of the following: Event.preventDefault();使用以下所有三个: Event.preventDefault(); , Event.stopPropagation(); , Event.stopPropagation(); , and return false; ,并return false; . . Each explained...每个解释...

The Event interface's preventDefault() method tells the user agent that if the event does not get explicitly handled, its default action should not be taken as it normally would be. Event 接口的 preventDefault() 方法告诉用户代理,如果事件没有得到显式处理,则不应像通常那样采取其默认操作。 (Source: MDN Webdocs .) (来源: MDN 网络文档。)

  • Event.stopPropagation(); : To stop the event from clicking a link within the containing parent's DOM (ie, if two links overlapped visually in the UI). :阻止事件点击包含父级的 DOM 中的链接(即,如果两个链接在 UI 中视觉上重叠)。

The stopPropagation() method of the Event interface prevents further propagation of the current event in the capturing and bubbling phases. Event 接口的 stopPropagation() 方法可防止当前事件在捕获和冒泡阶段进一步传播。 (Source: MDN Webdocs .) (来源: MDN 网络文档。)

  • return false; : To indicate to the onevent handler that we are cancelling the link-clicking behavior. : 向onevent处理程序表明我们正在取消链接单击行为。

The return value from the handler determines if the event is canceled.处理程序的返回值确定事件是否被取消。 (Source: MDN Webdocs .) (来源: MDN 网络文档。)

Full Working JSBin Demo. 完整的工作 JSBin 演示。

StackOverflow Demo... StackOverflow 演示...

 document.getElementById('my-link').addEventListener('click', function(e) { console.log('Click happened for: ' + e.target.id); e.preventDefault(); e.stopPropagation(); return false; });
 <a href="https://www.wikipedia.com/" id="my-link" target="_blank">Link</a>

The easiest way is just element.style.pointerEvents = "none";最简单的方法就是 element.style.pointerEvents = "none";

Someone mentioned something a bit similar above, but no need for any custom CSS - just set the style property directly in your JS and then back to "" when/if you want to re-enable it later.有人在上面提到了一些类似的东西,但不需要任何自定义 CSS - 只需直接在你的 JS 中设置 style 属性,然后当/如果你想稍后重新启用它时返回到 ""。

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.第一个解决方案是有效的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM