JavaScript 用于具有相同 id 的对象
我有以下代码:
HTML:
//forLoop (users)
<b>UserName</b>
<select id = "select-dropdown" onclick="showOptions()">
</select>
//endof forLoop
JavaScript:
function showOptions(){
var select = document.getElementById("select-dropdown");
var response = "option__option";
var optionList = response.split("__");
var size = optionList.length;
for(i = 0; i < size; i++){
select.innerHTML += "<option>" + optionList[i] + "</option>";
}
}
当我运行代码时,我有一个包含 10 个用户的列表,其中包含 10 个选择项,但下拉选项仅适用于第一个用户。
我猜测问题是由所有用户的相同 ID 引起的,我应该使用类似 this 的内容,但我在互联网上找不到任何具体答案
I have the following code:
HTML:
//forLoop (users)
<b>UserName</b>
<select id = "select-dropdown" onclick="showOptions()">
</select>
//endof forLoop
JavaScript:
function showOptions(){
var select = document.getElementById("select-dropdown");
var response = "option__option";
var optionList = response.split("__");
var size = optionList.length;
for(i = 0; i < size; i++){
select.innerHTML += "<option>" + optionList[i] + "</option>";
}
}
When I run the code I have a list of ten users with 10 select items but the drop-down option works only for the first user.
I'm guessing that the problem is caused by the same ID for all the users and I should use something like this but I can't find any specific answer on the internet
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您的 ID 必须是唯一的。您不能在同一页面上两次使用相同的 ID。
给他们上一堂课:
考虑使用 jQuery 作为您的 Javascript 框架,而不是尝试自己做事。它会节省您大量的时间和精力。
在 jQuery 中,您将能够使用简单的选择器获取所有选择元素:
您还可以删除当前正在使用的内联事件附件。在 HTML 中附加事件是不好的做法。
使用 jQuery:
更新
这是获取当前选择元素的示例,旧的 skool 方式: http://jsfiddle.net/G2ZuE/
Your ID's need to be unique. You cannot use the same ID twice on the same page.
Give them a class instead:
Consider using jQuery as your Javascript framework rather than trying to do things yourself. It'll save you much time and energy.
In jQuery you'll be able to obtain all of your select elements with a simple selector:
You'll also be able to get rid of your inline event attachment that you're curently using. Attaching events in the HTML is bad practice.
Using jQuery:
UPDATE
Here's an example of getting the current select element, the old skool way: http://jsfiddle.net/G2ZuE/
你不能将相同的ID分配给不同的html元素,你可以在选择的ID上附加一个后缀,并通过ID前缀或公共CSS类循环它们(如果你可以使用像JQuery或MooTools这样的库,那肯定会更简单) 。
请参阅此处获取纯 JavaScript 示例实现。
You cannot assign the same ID to different html elements, you can append a suffix to the select ID and cycle them by ID prefix or by common css class (and if you can use a lib like JQuery or MooTools it will be definitely more straightforward).
See here for a pure-javascript sample implementation.
你的猜测是正确的。此外,您应该将事件处理放在 JS 中而不是 HTML 中。下面的代码应该可以做到这一点。
HTML:
JavaScript
我希望这会有所帮助。
Your guess was correct. In addition you should put event handling in the JS not in the HTML. The following code should do it.
The HTML:
The JavaScript
I hope this helps.