简体   繁体   English

如果用户已经在 href 链接/链接指向的页面上,有没有办法禁用 href 链接/链接,而不使用 JQuery?

[英]Is there a way to disable href link / links if the user is already on the page the href link / links leads to, without using JQuery?

So I have something like this in my html:所以我的 html 中有这样的东西:

<a id="one" href="/index.html"> HOME </a>
<a id="two" href="/something.html"> SOMETHING </a>
<a id="three" href="/again.html"> AGAIN </a>

and if for example user is on page linked "..../index.html" and tries to click on "HOME" link button, it does nothing or fake redirects or its disabled to be clickable, same goes for other href buttons if the user is already on the page the buttons are redirecting to, and user tries to click on them, I have been looking everywhere but all solutions for this problem requires you to use JQuery, and I would like to not use libraries as much as possible, any solutions?例如,如果用户在链接“..../index.html”的页面上并尝试单击“HOME”链接按钮,它什么都不做或伪造重定向或禁用可点击,如果其他 href 按钮也是如此用户已经在按钮重定向到的页面上,并且用户试图点击它们,我到处都在寻找但是这个问题的所有解决方案都需要你使用 JQuery,我不想尽可能多地使用库,有什么解决办法吗?

For simplicity, add a class to all menu links in which you want this behavior为简单起见,将 class 添加到您想要此行为的所有菜单链接

<a class="locationLink" id="one" href="/index.html"> HOME </a>
<a class="locationLink" id="two" href="/something.html"> SOMETHING </a>
<a class="locationLink" id="three" href="/again.html"> AGAIN </a>

And check this:并检查这个:

var links = document.getElementsByClassName("locationLink");
for (var i = 0; i < links.length; i++) {
    var link = links[i];
    if (link.classList.contains('locationLink') && location.href == link.href) {
        link.addEventListener("click", function (event) {
            event.preventDefault();
        });
        break;
    }
}

Basically, you get all links and check only your locationLinks.基本上,您获得所有链接并仅检查您的位置链接。 If the current url is equals to the href, you add an event listener that blocks the navigation.如果当前 url 等于 href,则添加一个阻止导航的事件侦听器。 Maybe you need some debugging in the "location.href == link.href" because relative/absolute urls (you can refer to https://stackoverflow.com/a/44547904/18452174 ) but it's working.也许你需要在“location.href == link.href”中进行一些调试,因为相对/绝对 url(你可以参考https://stackoverflow.com/a/44547904/18452174 )但它正在工作。

If your menu can change dynamically, you can try this other approach:如果您的菜单可以动态更改,您可以尝试其他方法:

document.addEventListener("click", function (event) {
    var link = event.target;
    if (link.classList.contains('locationLink') && location.href == link.href) {
        link.addEventListener("click", function (event) {
            event.preventDefault();
        });
    }
}, false);

You do the same but check the condition in each document click instead only one time in document load.您也这样做,但检查每个文档中的条件,而不是在文档加载中只单击一次。

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

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