jQuery <select> 第一个 <option> 未禁用

标签 jquery css-selectors

我正在尝试进行选择,以便当用户从下拉列表中选择产品时,它会被禁用,因为每个产品所采取的操作不会超过一次。这可行,但如果您单击下拉列表,它仍然被选中但被禁用,我想自动选择第一个可用的 <option>没有禁用它以便能够选择它,故事结束;) 有什么线索吗?

$('#product_name').find('option:not([disabled]):first-of-type');
$('#product_name').find('option:not([disabled]):first-child');
$('#product_name').find('option:nth-child(1):not([disabled])');

当然我玩过:not(:disabled)也是,但是从我在这个主题上的测试时间来看,CSS选择器对于未禁用的元素工作得很好,但是当第二个 parameter === requisite 时发挥作用,这将是“选择第一个匹配规则的”一切都会变黑并且不起作用。

最佳答案

使用:first选择器:

The :first pseudo-class is equivalent to :eq( 0 ). It could also be written as :lt( 1 ). While this matches only a single element, :first-child can match more than one: One for each parent.

$('select option:not([disabled]):first').addClass('highlight');
.highlight {
  background: yellow;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>

<select>
  <option disabled>Disabled One</option>
  <option disabled>Disabled One</option>
  <option>Enabled One</option>
  <option>Enabled One</option>
  <option selected>Enabled One</option>
  <option disabled>Disabled One</option>
  <option disabled>Disabled One</option>
  <option>Enabled One</option>
</select>

关于jQuery <select> 第一个 <option> 未禁用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40314808/

相关文章:

css - 使用 CSS 选择 ID 的所有元素

CSS 使用 :not ID with CLASS

jquery - 如何使用旋转 css 以及 jQuery 可拖动 ASP.NET

javascript - 下拉选择图片

JavaScript : How to filter an array's contents into two resulting arrays

c# - OPC.测试.SmokeTest (TestFixtureSetUp) : SetUp : OpenQA. Selenium.InvalidSelectorException

html - :target to point to a . 类而不是 #id

css - 如何使用标准 CSS 选择器(nth-of-type 或 nth-child)为 Selenium 选择嵌套元素?

jquery - 是否有可能使 tfoot 出现在同一张表中的 tbody 之上?

javascript - 使用多维 JSON 填充表的有效方法