gpt4 book ai didi

javascript - 文档中点击链接的警报索引

转载 作者:行者123 更新时间:2023-12-02 16:21:35 25 4
gpt4 key购买 nike

需要编写函数来提醒文档中单击的链接的索引。例如:

 [html]
<body>
Links:<br/>
<a href="//www.yahoo.com">Yahoo!</a><br/>
<a href="//www.facebook.com">Facebook</a><br/>
<a href="//www.google.com">Google</a><br/>
</body>
[/html]

我的功能:

var as = document.getElementsByTagName('a');
for (i = as.length; i>= 0; i--) {
as[i].onclick = function() {
alert(i);
}
}

请帮我修复错误

最佳答案

The actual event occurs sometime in the future after your for loop has already finished running and thus its index is at the last value. You need to create some sort of closure that preserves the value of i uniquely for each event handler so they each have access to their own value. There are several different ways to do that, but all involve passing the i value to a function for each event handler.

演示@ fiddle

var as = document.getElementsByTagName('a');

for (var i=0, j=as.length; i<j; i++) {
var link = as[i];
(function(i){
link.onclick = function() {
alert (i);
}
}(i));
}

关于javascript - 文档中点击链接的警报索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29060399/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com