试图获取<a> tag onclick - no errors?

时间:2017-02-22 10:58:10

标签: javascript dom event-handling getelementsbytagname getattribute

Trying to simply identify if any tags are clicked on at anytime and get the href attribute of the clicked tag to store in the database.

To test i'm attempting to print out the href but nothing is printing on screen AND no errors in console? Any ideas?

// Anchor Tags - Capture the href of the link clicked
var aTags = document.getElementsByTagName('a');

for (var i = aTags.length - 1; i >= 0; --i) {
    aTags[i].onclick = function() {
    var aTagHref = aTags[i].getAttribute("href");
        alert(aTagHref);
    };
}

1 个答案:

答案 0 :(得分:2)

在事件监听器中,您不会拥有该元素数组,而且,您可以使用this来引用所点击的a

像这样:

&#13;
&#13;
var aTags = document.getElementsByTagName('a');

for (var i = aTags.length - 1; i >= 0; --i) {
    aTags[i].onclick = function() {
    var aTagHref = this.getAttribute("href");
        alert(aTagHref);
    };
}
&#13;
<a href="#asd">a</a>
<br />
<a href="#asdf">b</a>
<br />
<a href="#asdfg">c</a>
&#13;
&#13;
&#13;