简体   繁体   English

如何获取动态创建的下拉列表的值?

[英]How to get value of dynamically created dropdown list?

I instantiate a list of users in my DOM and then tie their name to the dropdown list.我在我的 DOM 中实例化一个用户列表,然后将他们的名字绑定到下拉列表中。 So they are not created until page load.所以它们在页面加载之前不会被创建。 I'm having trouble trying to target the <option> tag and access it's value.我在尝试定位<option>标记并访问它的值时遇到问题。

JS DOM Function JS DOM 函数

  let userDropDownList = userInstantiation.reduce((usersHTML, user) => {
    usersHTML += `<option class="nav__div__one__dropdown__choice" value="${user.id}">${user.name}</option>`
    return usersHTML;
  }, '')
  navDivDropdown.innerHTML = userDropDownList
}

I've tried to loop through the <option> tags but I'm returning empty an array.我试图遍历<option>标签,但我返回一个空数组。 My wrapper in my index.html is <select class="nav__div__one__dropdown" name="users"></select>我的index.html包装器是<select class="nav__div__one__dropdown" name="users"></select>

I'm attempting to get the value so that I can tye the user.id to the User instance and access those class methods.我正在尝试获取该值,以便我可以将 user.id 绑定到 User 实例并访问这些类方法。 Any tips would be greatly appreciated!任何提示将非常感谢!

You can do it using onchange event on the select input like so:您可以在选择输入上使用onchange事件,如下所示:

<select onchange="changed(this)"></select>

function changed(option){
 console.log(option.value);
}

Here is a working snippet这是一个工作片段

 let userInstantiation = [{id: 1, name: 'user1'},{id: 2, name: 'user2'}]; let userDropDownList = userInstantiation.reduce((usersHTML, user) => usersHTML += `<option class="nav__div__one__dropdown__choice" value="${user.id}">${user.name}</option>` , '') document.querySelector(".nav__div__one__dropdown").innerHTML = userDropDownList; function changed(option){ console.log(option.value); }
 <select class="nav__div__one__dropdown" onchange="changed(this)" name="users"></select>

you would go about it this way你会这样做

document.querySelector('nav__div__one__dropdown').addEventListner('change',(e)=>{
  const userId=e.target.value; 
  //here do your user tying logic 
})

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM