[英]onclick event not working with the links in javascript
I am new 2 javascript i have created function that adds onclick event & calls a user function to all my links in a page but it not working properly help me to solve this 我是新的2 javascript我已创建功能,添加onclick事件并调用用户功能到我在页面中的所有链接,但它不能正常工作帮我解决这个问题
<script type="text/javascript">
window.onload=function() {
var links = document.getElementsByTagName('a');
for(var i = 0, i<links.length; i++) {
links[i].onclick = function () {
var string = links[i].href; //href value
var str = string;
var spl = string.split("/");
switch(spl[2])
{
case 'www.google.com':
var str1 = "http://yahoo.com";
links[i].target="_blank";
links[i].href= str1;
break;
default:
links[i].href= string;
}
}
}
}
</script>
<a href="http://www.google.com/" target="-blank">www.google.com</a></br>
You have 2 problems: 你有2个问题:
1) You have a syntax error in your for loop. 1)for循环中存在语法错误。 You need to use semicolons instead of commas
您需要使用分号而不是逗号
for (var i = 0, i < elements.length; i++) {
vs VS
for (var i = 0; i < elements.length; i++) {
2) The onclick callback is referencing i. 2)onclick回调引用i。 The problem is, that you are changing i during your loop, but you only make the onclick callback later , after your loop completes.
问题是,您在循环期间正在更改i,但是您只能在循环完成后稍后进行onclick回调。 Hence the value of
i
is actually going to be 1
. 因此,
i
的值实际上将是1
。 And that means i
will be the same value for every single link you click. 这意味着
i
将为您单击的每个链接提供相同的值。 So, if you had 5 links, i
will be 6 for all of them (6 being the first breaking-value of your for loop) 所以,如果你有5个链接,
i
将为所有这些链接6(6个是你的for循环的第一个破坏值)
The important thing to remember here is onclick is called later, and you're updating i
before then. 这里要记住的重要事情是稍后调用onclick,然后你就会更新
i
。 To get around this problem, you can capture the value of i
at the time you define the onclick function like so: 要解决此问题,您可以在定义onclick函数时捕获
i
的值,如下所示:
window.onload = function () {
var elements = document.getElementsByTagName('a');
for (var i = 0; i < elements.length; i++) {
(function(index){
elements[index].onclick = function () {
var string = elements[index].href; //href value
var str = string;
var spl = string.split("/");
switch (spl[2]) {
case 'www.google.com':
var str1 = "http://yahoo.com";
elements[index].target = "_blank";
elements[index].href = str1;
break;
default:
elements[index].href = string;
}
}
})(i);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.