javascript 在下拉javascript eventlistener中选择时触发事件
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/29269948/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Trigger event when selecting in a dropdown javascript eventlistener
提问by John Arellano
I have this javascript function,
我有这个 javascript 功能,
function listQ(){
var e = document.getElementById("list");
if(e.selectedIndex > 0){
if("Blank Test" === e.selectedIndex){ alert("yo"); }
}
}
My problem is how to trigger the function when selected the same value of dropdown list?
我的问题是如何在选择相同的下拉列表值时触发该功能?
I tried this code,
我试过这个代码,
document.getElementById("list").addEventListener("change",listQ);
And it must use an event listener.
并且它必须使用事件侦听器。
回答by Tommaso Boggia
You can use the onchange
method on your select element.
您可以onchange
在选择元素上使用该方法。
var changedText = document.getElementById('changed');
function listQ(){
changedText.textContent = this.value;
}
document.getElementById("list").onchange = listQ;
For this HTML
对于这个 HTML
<select id="list">
<option value="1">One</option>
<option value="2">Two</option>
<option value="3">Three</option>
<option value="4">Four</option>
</select>
<p>
Your value <spam id="changed"></spam>
</p>
Here is a Fiddleforked from Jonathan, and here is MDN documentation for the changeevent.
回答by Jonathan
The line "Blank Test" isn't going to work because e.selectedIndex
is going to be an index (a number). You could use e.options[e.selectedIndex].value
“空白测试”行将不起作用,因为e.selectedIndex
它将成为一个索引(一个数字)。你可以用e.options[e.selectedIndex].value
Apart from that, just change the event listener to "click" instead of "change":
除此之外,只需将事件侦听器更改为“单击”而不是“更改”:
<select id="list">
<option value="1">One</option>
<option value="2">Two</option>
<option value="3">Three</option>
<option value="Blank Test">Four</option>
</select>
<script type="text/javascript">
function listQ(){
var e = document.getElementById("list");
if(e.selectedIndex > 0){
if("Blank Test" === e.options[e.selectedIndex].value){ alert("yo"); }
}
}
document.getElementById("list").addEventListener("click",listQ);
</script>
Here's a Fiddle to demonstrate: https://jsfiddle.net/h81pcpm0/
这里有一个 Fiddle 来演示:https: //jsfiddle.net/h81pcpm0/
回答by Viet Anh
I've solved your problem here: https://jsfiddle.net/evL4cc5q/
我在这里解决了你的问题:https: //jsfiddle.net/evL4cc5q/
var lastIndex = "";
function listQ(){
var e = document.getElementById("list");
if(e.selectedIndex > 0){
if(e.selectedIndex != lastIndex) {
if("Blank Test" === e.options[e.selectedIndex].value)
alert("yo");
lastIndex = e.selectedIndex;
}
else {
lastIndex = "";
}
}
}
document.getElementById("list").addEventListener("click",listQ);