jquery:[]选择器? [英] jquery :[] selector?

查看:75
本文介绍了jquery:[]选择器?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

给定一个SELECT元素:

 < select> 
< option> foo< / option>
< option>栏< / option>
< option> baz< / option>
< / select>

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



这不起作用:

  $('option [text =bar]' ).attr('selected',true); 

然而,这确实有效:

  $('option:[text =bar]')。attr('selected',true); 

为什么?

现场演示:< a href =http://jsfiddle.net/YbfqZ/2/ =nofollow> http://jsfiddle.net/YbfqZ/2/

querySelectorAll 的选择器,因为它是无效的。

因此,它默认为Sizzle,它可以容忍冒号,尽管它在技术上不被支持(这意味着它可能会在未来破裂)。 Sizzle会检查属性和属性。因此,它不会找到一个 text 属性,但它会找到<$ c>的文本属性$ c>< option> 元素。



下面是一个示例,它演示了Sizzle将匹配一个属性,而不仅仅是一个属性,它的属性等于选择器。






来自示例的代码

  //在最后一个选项
$('#id option')中设置一个自定义属性,slice(-1)[0] .customProp ='customValue';

//打破选择器:我们默认为Sizzle,
//它符合我们的定制属性
$('#id option:[customProp =customValue]' ).attr('selected',true);






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


Given a SELECT element:

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

I want to select the OPTION element with the value "bar".

This doesn't work:

$('option[text="bar"]').attr('selected', true);

However, this does work:

$('option:[text="bar"]').attr('selected', true);

Why?

Live demo: http://jsfiddle.net/YbfqZ/2/

解决方案

The reason for that behavior is that your colon breaks the selector for querySelectorAll because it isn't valid.

As such, it defaults to Sizzle, which will tolerate the colon, even though it technically isn't supported (which means it could break in the future). Sizzle will check for both attributes and properties. As such, it won't find a text attribute, but it will find the text property of the <option> element.

Here's an example that demonstrates that Sizzle will match a property instead of just an attribute with its attribute-equals selector.


Code from example:

  // 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);


EDIT: My example link previously referenced someone else's example because I typed the wrong revision number. Fixed.

这篇关于jquery:[]选择器?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆