Get current value from datalist onhover

微笑、不失礼 提交于 2019-12-08 17:08:02

问题


I'm trying to get the current value of the hovered element of a datalist. So if I open the datalist with values in it and just move my mouse over them, I want the values to appear in the console.

This is my attempt:

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

$("#browsers").on("mouseover", function() {
  console.log($(this).value());
});

And here is a fiddle: https://jsfiddle.net/sshcvr5q/


回答1:


I'm not sure this is going to be possible. Datalist options, whilst still visible in the main document DOM tree, get cloned and encapsulated as part of a Shadow DOM tree, and as aren't accessible from the parent document. It is these encapsulated Shadow DOM nodes that you're actually hovering over (certainly in Chrome anyway), and the original node in the main DOM tree does not get triggered with a mouseover or hover event when you hover over the Shadow DOM nodes.

If you use Chrome DevTools to inspect the DOM tree in your JSFiddle example, you can see the Shadow Root of the encapsulated DOM tree:

See this explanation from another Stack Overflow question for further information about why you can't listen for events on the Shadow DOM from the parent document.




回答2:


I think you have to check $("#browser") and not $("#browsers")

But anyway you will receive the value on onchange better :)

Regards



来源:https://stackoverflow.com/questions/35894243/get-current-value-from-datalist-onhover

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!