使用addEventListener和getElementsByClassName传递元素ID [英] Using addEventListener and getElementsByClassName to pass an element id

查看:435
本文介绍了使用addEventListener和getElementsByClassName传递元素ID的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在定义JSON文件中的项目列表,并将该列表显示在网页上.目的是让用户单击该列表中的任何项目以显示有关该项目的更多信息(保存在同一JSON文件中的信息).

I'm defining a list of items from a JSON file and displaying that list on a web page. The intention is for users to click on any item in that list to display more information on that item (information that is held in the same JSON file).

该列表中的所有项目都是同一类的成员,并且每个项目都有一个从JSON文件定义的唯一ID. HTML看起来像这样:

All items of that list are members of the same class, and each has a unique id defined from the JSON file. The HTML looks something like this:

<ul>
   <li class="menu" id="bob">Robert Smith</li>
   <li class="menu" id="jane">Jane Doe</li>
   <li class="menu" id="sue">Susan Carter</li>
</ul>

我打算按照

var userSelection = document.getElementsByClassName('menu');

userSelection.addEventListener('click', myFunctionToPrintDetails());

但是我不确定如何将ID从事件侦听器传递到打印函数,以便确定要打印的详细信息.

but I am not sure how to pass the id from the event listener to the print function in order to determine which details to print.

我在HTML/CSS方面有很多经验,而在JSON/AJAX方面却很少,因此我可能会尝试完全低音处理.如果有更合适的方法可以做到这一点,我欢迎您提供反馈.

I have a lot of experience with HTML/CSS but very little with JSON/AJAX, so possible I'm going about this completely bass-ackwards. If there is a more appropriate way to get this done I'm open to the feedback.

我尝试了两种答案,但均无济于事.当我将userSelection.length登录到控制台时,我得到0;当我登录userSelection时,我得到:

I tried both answers but neither worked. When I log userSelection.length to the console I get 0; when I log userSelection I get:

HTMLCollection(0)
> sue: li#sue.menu
length: 3
> jane: li#jane.menu
> bob: li#bob.menu
> 0: li#bob.menu
> 1: li#jane.menu
> 2: li#sue.menu

推荐答案

codepen演示

var userSelection = document.getElementsByClassName('menu');

for(var i = 0; i < userSelection.length; i++) {
  (function(index) {
    userSelection[index].addEventListener("click", function() {
       console.log("Clicked index: " + index);
     })
  })(i);
}

如@torazaburo在评论中所指出的,如果要支持的浏览器符合JavaScript的最新版本ECMAScript 6(ES6),则可以使用以下内容.

As pointed out by @torazaburo in the comments, you can use the following if the browsers you want to support are complying with ECMAScript 6 (ES6), the newest version of JavaScript.

var userSelection = document.getElementsByClassName('menu');

for(let i = 0; i < userSelection.length; i++) {
  userSelection[i].addEventListener("click", function() {
    console.log("Clicked index: " + i);
  })
}

这篇关于使用addEventListener和getElementsByClassName传递元素ID的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆