简体   繁体   中英

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". 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? I'd like to throw in that variable where it says " http://www.example.com ". I tried elements[i].href but it says it's undefined.

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'

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? 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:

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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