问题
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