且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

jquery:[]选择器?

更新时间:2023-10-14 22:44:22

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.

相关阅读

推荐文章