javascript - 在没有 jQuery 的情况下获取 HTML 中的选定选项

标签 javascript node.js dom

我在每个 <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')失败

valid pseudo selectors

: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/

相关文章:

javascript - 单击提交按钮时,实时预览中的 html js 项目不断刷新,结果所需页面在几秒钟内闪烁

javascript - 像 Google 一样带有后退按钮的登录页面

javascript - 正确的 JavaScript 运算符优先级表是什么?

node.js - 如何在sqlite nodejs select查询中获取整个结果集?

javascript - 无法将图像对象与其他 HTML 元素一起放置

javascript - 我可以限制添加到数组中的项目数量吗?

node.js - 部署到 App Engine 后运行 Sequelize 迁移

javascript - date.getFullYear 不是 while() 内的函数

javascript - 重点播放视频

java - 使用 Java DOM 解析器在 XML NODE 中创建换行符