如何在点击数据列表选项列表时触发事件? [英] How to fire an event on clicking data list option list?
问题描述
我有一个看起来像这样的数据列表:
I have a datalist that looks like :
<datalist id="foodlist">
<option value="one" ></option
<option value="two" ></option>
<option value="three" ></option>
</datalist>
<input type="text" list="foodlist" autocomplete=true id="inputItem"/>
当用户使用JavaScript在列表中选择某个选项时,我希望触发一个事件.
I want an event to fire when user selects on of the option in the list using JavaScript.
如何实现?
onClick,onChange似乎不起作用.
onClick, onChange does not seem to work.
推荐答案
我知道这有点旧,但是我认为应该在某个地方进行记录.如果您试图从下拉选择中检测输入,而不是单击本身,则可以使用"input"事件并检查传递的事件对象的类型-剪切/粘贴/按键输入将传递"InputEvent"对象,而数据列表选择将传递通用的事件"对象.
I know this is kind of old, but I thought I should document it somewhere. If you're trying to detect input from a dropdown selection rather than a click per se, you can use the "input" event and check the type of the passed event object - cut/paste/keypress input will pass an "InputEvent" object, whereas a datalist selection will pass a generic "Event" object.
var textbox = document.getElementById("inputItem");
textbox.addEventListener("input", function(e){
var isInputEvent = (Object.prototype.toString.call(e).indexOf("InputEvent") > -1);
if(!isInputEvent)
alert("Selected: " + e.target.value);
}, false);
<datalist id="foodlist">
<option value="one" ></option>
<option value="two" ></option>
<option value="three" ></option>
</datalist>
<input type="text" list="foodlist" autocomplete=true id="inputItem"/>
这篇关于如何在点击数据列表选项列表时触发事件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!