【发布时间】:2017-06-28 22:44:54
【问题描述】:
我正在尝试为 <select> 的 <option> 制作 JavaScript,其中包含 2 个项目,但一旦选择其中一个,我似乎无法执行任何事件。这是我的代码:
var e1 = document.getElementById("#selector").option[0].text;
var e2 = document.getElementById("#selector").option[1].text;
var e3 = document.getElementById("#selector").option[2].text;
document.querySelector("e1").addEventListener("click", myInfo, false);
function myInfo(){
alert("Test");
}
<select id="selector">
<option value="" disabled="disabled" selected="selected">Select a layout</option>
<option value="1">One</option>
<option value="2">Two</option>
</select>
【问题讨论】:
-
如果您使用 jQuery 库,这会容易得多。这对你来说是一个选择吗?
-
您能告诉我们您要解决什么问题吗?此外,
document.querySelector("e1")正在寻找元素<e1>,而您可能 - 或应该 - 寻找<select>元素,document.getElementById('selector');或document.querySelector('#selector') -
@GentlemanMax 这不是问题,他要求 Js 解决方案。使用Jquery之前最好先学JS
-
@Alexis,这就是为什么它是评论而不是解决方案。我也倾向于不同意在大多数情况下你需要在 jQuery 之前掌握 JS 的想法,尽管这几乎不是讨论它的地方。
-
@GentlemanMax,不是所有东西都需要 jQuery。没有必要添加一个庞大的库来让事情变得“简单”,如果你真的学会了 js,这很容易
标签: javascript html select option