[英]Javascript get anchor href on click
How can I get the href of an anchor when I click on it using javascript? 当我使用javascript点击它时,如何获得锚点的href? I did the following:
我做了以下事情:
function myFunc() {
}
window.onclick = myFunc;
But how to extend the function to respond only to clicks on anchors and get the href? 但是如何扩展函数只响应锚点上的点击并获得href?
function linkClick(e) { alert(e.target.href); } links = document.getElementsByTagName('a'); for (i = 0; i < links.length; i++) links[i].addEventListener('click', linkClick, false);
Your document.onclick
registers the handler on the whole document. 您的
document.onclick
在整个文档中注册处理程序。 But you should add it to every link. 但是你应该把它添加到每个链接。 You can do this with JavaScript and using a framework like Prototype or jQuery makes it a lot easier:
您可以使用JavaScript执行此操作并使用Prototype或jQuery等框架使其更容易:
$$('a').invoke('observe', 'click', function(a){
myFunc(a);
});
But you can also use pure JS combining the getElementsByTagName
function with a loop (see Delan's new answer). 但是你也可以使用纯JS将
getElementsByTagName
函数与循环结合起来(参见Delan的新答案)。
it won't work like this, you need to setup an onclick handler for every anchor. 它不会像这样工作,你需要为每个锚设置一个onclick处理程序。 The easiest way to do this, is to use a javascript framework like jQuery or Prototype or something similar.
最简单的方法是使用jQuery框架,如jQuery或Prototype或类似的东西。
extend your function to recieve the calling object: 扩展您的函数以接收调用对象:
var myFunc = function(target) {
var href = target.href;
// ... your function code that can now see the href of the calling anchor
}
jQuery: jQuery的:
$('a').click(function(){
myFunc(this);
});
function myFunc(link) {
alert(link.href);
return false; // return false if you don't want to actually navigate to that link
}
<a href onclick="return myFunc(link)">something</a>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.