在不使用jQuery的情况下获取HTML中的选定选项
我在每个<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
中工作正常,并且对于select器起作用:checked
在浏览器中:checked
(在checkboxinput上),而不是对于select器:selected
,这是奇怪的。
我收到错误(在Chrome中):
未捕获SyntaxError:未能执行“元素”上的“匹配”:“:已select”不是有效的select器。
错误消息似乎是正确的:selected
不是一个有效的select器,甚至querySelector('option:selected')
失败
有效的伪select器是
: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
MDN表示 ,使用正确的伪造类将会被:checked
:checked
CSS伪类select器代表:checked
任何无线电(<input type="radio">
),checkbox(<input type="checkbox">
) 或选项(<option>
切换到开启状态 。