简体   繁体   中英

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

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

1) You have a syntax error in your for loop. You need to use semicolons instead of commas

for (var i = 0, i < elements.length; i++) {

vs

for (var i = 0; i < elements.length; i++) {

2) The onclick callback is referencing i. The problem is, that you are changing i during your loop, but you only make the onclick callback later , after your loop completes. Hence the value of i is actually going to be 1 . And that means i will be the same value for every single link you click. So, if you had 5 links, i will be 6 for all of them (6 being the first breaking-value of your for loop)

The important thing to remember here is onclick is called later, and you're updating i before then. To get around this problem, you can capture the value of i at the time you define the onclick function like so:

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);

    }
}

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