我正在尝试为其中包含2个项目的<select>
's制作JavaScript <option>
,但是一旦选择其中之一,我似乎将无法执行任何事件。这是我的代码:
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>
您的选择元素看起来不错。但是您的代码需要更改:
var selector = document.getElementById("selector")
selector.addEventListener("change", function(){
alert(selector.options[selector.selectedIndex].text);
});
这就是您所需要的。不要忘记在您的代码中提及
var e3 = document.getElementById("#selector").option[2].text;
要通过ID选择,只需写“ selector”而不是“ #selector”。它被称为“选项”而不是“选项”。
我希望这有帮助
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句