我在每个 <option>
上使用以下函数判断是否被选中:
var _matches = function(el, selector) {
var fn = el.matches || el.matchesSelector || el.msMatchesSelector || el.mozMatchesSelector || el.webkitMatchesSelector || el.oMatchesSelector;
return fn.call(el, selector);
};
它在 jsdom
中运行良好在 NodeJS 中,它适用于选择器 :checked
(在复选框输入上)在浏览器中,但不是选择器 :selected
,这很奇怪。
我收到错误(在 Chrome 中):
Uncaught SyntaxError: Failed to execute 'matches' on 'Element': ':selected' is not a valid selector.
最佳答案
错误信息似乎是正确的,:selected
不是有效的选择器,甚至 querySelector('option:selected')
失败
:active
:checked
:default
:dir()
:disabled
:empty
:enabled
:first
:first-child
:first-of-type
:fullscreen
:focus
:hover
:indeterminate
:in-range
:invalid
:lang()
:last-child
:last-of-type
:left
:link
:not()
:nth-child()
:nth-last-child()
:nth-last-of-type()
:nth-of-type()
:only-child
:only-of-type
:optional
:out-of-range
:read-only
:read-write
:required
:right
:root
:scope
:target
:valid
:visited
要使用的正确伪类应该是 :checked
, MDN says
The
:checked
CSS pseudo-class selector represents any radio (<input type="radio">
), checkbox (<input type="checkbox">
) or option (<option>
in a<select>
) element that is checked or toggled to an on state.
关于javascript - 在没有 jQuery 的情况下获取 HTML 中的选定选项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30104505/