简体   繁体   中英

Retrieve the index ul li a list

I have a list which, when clicked, gives me its index. The problem I have is that the first time I click, it does not do the action in its entirety. I have to re-click on it and then everything works perfectly. But I can not find the problem. Can you tell me where I make my mistake?

Here's my list:

<ul id="filesList">
  <li>index 1</li>
  <li>index 2</li>
  <li>index 3</li>
</ul>

Thank you very much for your help!

Here's my code:

filesList.addEventListener('click', function(e) {
for (var i = 0, len = filesList.children.length; i < len; i++) {
    (function(index) {
        filesList.children[i].onclick = function() {
            console.log(files[index]);
            e.stopImmediatePropagation();
        }
    })(i);
  }
});

You are adding the event listener to each li on the click event of the list. That means that you have to click the list once to set the behavior for each item click.

The solution is very simple, you just have to remove the first and last line:

for (var i = 0, len = filesList.children.length; i < len; i++) {
    (function(index) {
        filesList.children[i].onclick = function() {
            console.log(files[index]);
            e.stopImmediatePropagation();
        }
    })(i);
}

Then, when the code loads it will set the click event for each item on the list.

Update: this javascript should run after the list is created.

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