[英]Select option html in JavaScript
我正在尝试为其中包含2个项目的<select>
的<option>
创建JavaScript,但是一旦选择其中之一,我似乎将无法执行任何事件。 这是我的代码:
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>
我认为您不了解这些功能(尤其是querySelector
如何工作。
您应该改为使用更改事件:
var val;
document.getElementById("selector").addEventListener("change",function(){
val = this.value; // or document.getElementById("selector").value
// then use your value to do other things
});
ps请在网上搜索querySelector
方法的使用。 显然,您不知道它是如何工作的。
您的选择元素看起来不错。 但是您的代码需要更改:
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”。 它被称为“选项”而不是“选项”。
我希望这有帮助
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.