[英]Trigger event when option element selected (No jQuery)
这个问题已经问了很多遍了,但是我看到的所有答案都使用了jQuery,而我不能在该项目中使用它。 当我从选择元素内的列表中选择了选项元素“其他”时,我正在尝试执行代码。
使用“更改”作为事件似乎无效。
document.querySelector("#title").addEventListener("change", (event) => { if (event.target.textContent === "Other") { console.log("Other Selected"); } });
<select id="title" name="movie_title"> <option value="titanic">Titanic</option> <option value="avatar">Avatar</option> <option value="other">Other</option> </select>
您可以使用onchange
事件,该事件在每次select选项更改时触发:
function myfunction(value) { console.log("changed to "+value+"!") }
<select onchange="myfunction(this.value)" id="title" name="movie_title"> <option value="titanic">Titanic</option> <option value="avatar">Avatar</option> <option value="other">Other</option> </select>
另一种解决方案是添加event listener
:
document.getElementById("title").addEventListener("change", (event) => {
// run your code
});
document.getElementById("title").addEventListener("change", (event) => { console.log("changed to: " + event.target.value + "!"); });
<select id="title" name="movie_title"> <option value="titanic">Titanic</option> <option value="avatar">Avatar</option> <option value="other">Other</option> </select>
使用event.target.value
document.getElementById("title").addEventListener("change", (event) => { console.log(event.target.value); });
<select id="title" name="movie_title"> <option value="titanic">Titanic</option> <option value="avatar">Avatar</option> <option value="other">Other</option> </select>
为了获得预期的结果,请使用event.target.value,而不是textContent,它将提供所有选项而不是所选选项
document.querySelector("#title").addEventListener("change", (event) => {
if (event.target.value === "other") {
console.log("Other Selected");
}
});
代码示例-https: //codepen.io/nagasai/pen/JLoNMK?editors=1010
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.