我在将onclick 附加到循环内的每个链接对象时遇到问题,当您单击链接时,它似乎总是返回与循环中的第一项相关的数据,无论单击了什么。我需要点击每个链接以获得该链接的相关href
在下面的示例中,无论单击哪个链接,console.log 都将始终显示“ http://example.com/link1/ ”
HTML 示例
<li>
<h2><a class="t" href="http://example.com/link1/"><i>Link 1 text</i></a></h2>
<div class="panel" >Content</div>
</li>
<li>
<h2><a class="t" href="http://example.com/link2/"><i>Link 2 text</i></a></h2>
<div class="panel" >Content</div>
</li>
<li>
<h2><a class="t" href="http://example.com/link3/"><i>Link 3 text</i></a></h2>
<div class="panel" >Content</div>
</li>
</ul>
JavaScript:
(function(){
var theh2s = document.getElementById("panelList").getElementsByTagName("h2"),
i = theh2s.length;
while (i--) {
var getTheLinks = theh2s[i].getElementsByTagName("a");
if (getTheLinks){
if (getTheLinks[0].href){
console.log(getTheLinks[0].href);
getTheLinks[0].onclick = function() {
console.log(getTheLinks[0].href);
_gaq.push(['_trackEvent', 'Homepage', 'AB Click - Test B', getTheLinks[0].href]);
};
}
}
}
})();