简体   繁体   中英

addEventListener click for Unordered List

Attempting to convert a for loop that steps through an unordered list of hyperlinks adding an 'onclick' function to each into one using an eventlistener for an assignment. I have been unable to get a working model.

Here is the navlist and links I am working with, note that these I cannot edit or change in any way.

    <body>

<ul id="navlist">
    <li id="l0"> <a href="#">Sniffer</a>    </li>
    <li id="l1"> <a href="#">is</a> </li>
    <li id="l2"> <a href="#">good</a> </li>
    <li id="l3"> <a href="#">programmer</a> </li>
</ul>
<script>

var myLinks = [
                'http://bing.com/search?q=Sniffer',
                'http://bing.com/search?q=is',
                'http://bing.com/search?q=good',
                'http://bing.com/search?q=programmer'
                ];

And here is the code sample that I am converting:

window.onload=function() {

  for (var i=0; i< myLinks.length; i++) {
    // document.getElementById("l"+i).getElementsByTagName("a")[0]).href=myLinks[i];
      document.getElementById("l"+i).getElementsByTagName("a")[0].onclick=(function(idx) {
      var idx = i;
      return function() {  
        window.location.href = myLinks[idx]; 
        return false; // cancel href
        }; 
    })(i);      
  }
}
</script> 
</body>

I have attempted a few different ways of formatting the specific document elements in the concatenation. but none of them work. Here is my most recent and simplest attempt:

window.onload=function() {

  for (var i=0; i< myLinks.length; i++) {
      document.getElementById("l"+i).addEventListener("click", function() {
      var idx = i;
      return function() {  
        window.location.href = myLinks[idx]; 
        return false; // cancel href
        }; 
    })(i);      
  }
}

I very much need help with this as I have tried to work with this code for a decent number of hours. I don't really even understand what the code is doing to be able to convert to a click event. Thanks in advance.

Event delegation is a nice solution to this problem:

var myLinks = [
    'http://bing.com/search?q=Sniffer',
    'http://bing.com/search?q=is',
    'http://bing.com/search?q=good',
    'http://bing.com/search?q=programmer'
];

var list = document.getElementById('list');

list.addEventListener('click', function (event) {

    if (event.target && event.target.nodeName === "A") {
        event.preventDefault();
        var index = Array.prototype.indexOf.call(list.children, event.target.parentNode);
        var href = myLinks[index];
        console.log('link to ' + href + ' was clicked.');
        // window.location = href;
    }

});

Fiddle

You can do it this way:

var myLinks = [
    'http://bing.com/search?q=Sniffer',
    'http://bing.com/search?q=is',
    'http://bing.com/search?q=good',
    'http://bing.com/search?q=programmer'];

window.onload = function() {
    for (var i = 0, len = myLinks.length; i < len; i++) {
        document.getElementById("l" + i).addEventListener("click", (function (idx) {
            return function () {
                window.location.href = myLinks[idx];
                return false; // cancel href
            };
        })(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