[英]Click a link with href attribute and execute the Javascript function
My script contains a link a
element with href
attribute of "#login" as below. 我的脚本包含一个链接,
a
元素具有href
属性为“ #login”,如下所示。
<a href="#login">Login</a>
I want to my Javascript function detect the "href" element in the link and execute. 我想让我的Javascript函数检测链接中的“ href”元素并执行。 How can I do this?
我怎样才能做到这一点? My Javascript function is
我的Javascript函数是
window.onload = function() {
document.getElementsByTagName("a[href=#login]").onclick = function(e) {
e.preventDefault();
alert("working");
}
}
Why have I seen no querySelector love in these answers? 为什么在这些答案中没有看到querySelector喜欢?
If you want to use that CSS selector to grab your link, nothing is stopping you: 如果要使用该CSS选择器来获取链接,则没有什么可以阻止您:
window.onload = function() { document.querySelector("a[href='#login']").onclick = function(e) { e.preventDefault(); alert("working"); } }
<a href="#login">Login</a>
EDIT: I saw in another answer that you believe there may be multiple links on a page that match that selector, in which case you'll need to loop through them: 编辑:我在另一个答案中看到,您认为页面上可能存在与该选择器匹配的多个链接,在这种情况下,您需要遍历它们:
window.onload = function() { var links = document.querySelectorAll("a[href='#login']"), //always create anonymous functions outside of a loop :) click = function(e) { e.preventDefault(); alert("working"); }, i; for (i = 0; i < links.length; i++) { links[i].onclick = click; } }
<a href="#login">Login</a> <a href="#login">Login</a>
Your getElementsByTagName
is treating it like a jquery selector, which it is not designed to do. 您的
getElementsByTagName
将其像jquery选择器一样对待,这并不是设计出来的。
It would be much simpler to give the tag an id
and use getElementById
: 为标签提供一个
id
并使用getElementById
会容易得多:
window.onload = function() { document.getElementById("loginLink").onclick = function(e) { e.preventDefault(); alert("working"); } }
<a href="#login" id="loginLink">Login</a>
If for whatever reason you cannot change the html and you want to do it this way you would need to get all a
tags then loop through each one to test the href
attribute. 如果因任何原因,你不能改变的HTML,你想这样做,这样你就需要把所有
a
标签,然后遍历每一个测试href
属性。 Note you need to use a.getAttribute("href")
to get "#login", rather than just a.href
which oftens give you an full URL: 请注意,您需要使用
a.getAttribute("href")
来获取“ #login”,而不仅仅是a.href
,它通常会为您提供完整的URL:
window.onload = function() { var aTags = document.getElementsByTagName("a"); for(var i = 0; i < aTags.length; i++) { var a = aTags[i]; if(a.getAttribute("href") == "#login") { a.onclick = function(e) { e.preventDefault(); alert("working"); } } } }
<a href="#login">Login</a> <a href="#test">Test</a> <a href="#login">Login Again</a>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.