Html 输入列表选择更改事件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15147728/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-29 05:59:50  来源:igfitidea点击:

Input List Selection Changed Event

htmllisteventsinputhtml-datalist

提问by swamprunner7

I have this example:

我有这个例子:

<datalist id="browsers">
  <option value="Internet Explorer">
  <option value="Firefox">
  <option value="Google Chrome">
  <option value="Opera">
  <option value="Safari">
</datalist>

I need to catch an event, when the user selects option (with mouse or keyboard).

当用户选择选项(使用鼠标或键盘)时,我需要捕获一个事件

I tried to do onchange="MySuperFunction();", but this works only when an item is selected and then the list is unfocused.

我尝试这样做onchange="MySuperFunction();",但这仅在选择了一个项目然后列表未聚焦时才有效。

回答by Explosion Pills

The inputevent should work for what you need. As I understand, you can't use a datalist directly, but it is connected to an input by the listattribute. This event binding would go on that input:

input事件应该适合您的需要。据我了解,您不能直接使用数据列表,但它通过list属性连接到输入。此事件绑定将继续该输入:

document.getElementById('browsers-input').addEventListener('input', function () {
   console.log('changed'); 
});

http://jsfiddle.net/vccfv/

http://jsfiddle.net/vccfv/

回答by Olivier Royo

To get the same effect of "Explosion Pills" solution using JQuery style:

要使用 JQuery 样式获得与“Explosion Pills”解决方案相同的效果:

$("#browsers-input").on("input", MySuperFunction);

回答by martriay

Usin jQueryyou could use .changehttp://jquery.com/

使用设jQuery你可以使用.changehttp://jquery.com/

$('datalist#browsers').change(MySuperFunction);

or

或者

$('datalist#browsers').change(function(){
  // stuff
});