给定一个 SELECT 元素:

<select>
    <option>foo</option>
    <option>bar</option>
    <option>baz</option>
</select>

我想选择值为“bar”的 OPTION 元素。

这不起作用:
$('option[text="bar"]').attr('selected', true);

但是,这确实有效:
$('option:[text="bar"]').attr('selected', true);

为什么?

现场演示:http://jsfiddle.net/YbfqZ/2/

最佳答案

这种行为的原因是您的冒号破坏了 querySelectorAll 的选择器,因为它无效。

因此,它默认为 Sizzle,它可以容忍冒号,即使它在技术上不受支持(这意味着它将来可能会中断)。 Sizzle 将检查属性和属性。因此,它不会找到 text 属性,但会找到 text 元素的 <option> 属性。

Here's an example 表明 Sizzle 将匹配一个属性,而不仅仅是一个属性与其 attribute-equals 选择器。

示例代码:

  // set a custom property on the last option
$('#id option').slice(-1)[0].customProp = 'customValue';

  // breaking the selector with : we default to Sizzle,
  //    which matches our custom property
$('#id option:[customProp="customValue"]').attr('selected', true);

编辑: 我的示例链接之前引用了别人的示例,因为我输入了错误的修订号。固定的。

10-08 09:48