[英]Javascript attach an onclick event to all link with href variable
I am attempting to add an onclick function to all my links with the class of "external-link". 我试图为我的所有带有“外部链接”类的链接添加onclick函数。 So I've successfully done it and did a test where anytime I click on one it alerts "it works" but how do return the href of that link into the function?
因此,我已经成功完成了该测试,并在我单击该按钮的任何时候都进行了测试,以提醒它“起作用”,但是该链接的href如何返回到函数中呢? I'd like to throw in that variable where it says " http://www.example.com ".
我想在该变量中输入“ http://www.example.com ”。 I tried elements[i].href but it says it's undefined.
我尝试了elements [i] .href,但它是未定义的。
var elements = document.getElementsByClassName('external-link');
for(var i = 0, len = elements.length; i < len; i++) {
elements[i].onclick = function () {
trackOutboundLink(‘http://www.example.com’); return false;
}
}
The context of your onclick callback will be the link that's clicked so you can simply use 'this.href' 您的onclick回调的上下文将是被单击的链接,因此您可以简单地使用'this.href'
var elements = document.getElementsByClassName('external-link');
for(var i = 0, len = elements.length; i < len; i++) {
elements[i].onclick = function () {
trackOutboundLink(this.href); return false;
}
}
Have you considered using jQuery for this? 您是否考虑过为此使用jQuery? It helps keep a straightforward and clean code, compatible to most browsers, and frees you from dealing with complex object trees.
它有助于保持简单明了的代码,与大多数浏览器兼容,并使您无需处理复杂的对象树。
<html> <head> <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script> <script> $(document).ready(function(){ $("a.external-link").click(function(){ alert("You clicked an external link to: " + $(this).attr("href")); }); }); </script> </head> <body> <a class="external-link" href="http://www.example1.com">Example 1</a><br> <a class="external-link" href="http://www.example2.com">Example 2</a><br> <a class="internal-link" href="http://www.example3.com">Example 3</a> - <i>no alert</i> </body> </html>
Resources: 资源:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.