Why does *[checked] not match a single checked inp

2020-07-23 08:42发布

Lets say I have a checkbox with id 'test' and its on a page loaded with jQuery 1.5.2.

<input id="test" type="checkbox"/>

Now if I click on the checkbox to set it in the checked state...

Why does $("#test").is(":checked") return true and $("#test").is("*[checked]") return false.

Here's a jsFiddle with the described scenario

5条回答
神经病院院长
2楼-- · 2020-07-23 08:55

The checkedness of a checkbox is reflected in the object property checked. It can be set by the DOM attribute checked, but the direction is one-way: the DOM attribute does not get updated when the object's property changes. :checked is a dedicated pseudoselector which will check the object's property; [checked] is a selector which checks for the existence of the DOM attribute.

查看更多
再贱就再见
3楼-- · 2020-07-23 09:04

See the discussion of the checked property on the jQuery property page:

http://api.jquery.com/prop/

查看更多
在下西门庆
4楼-- · 2020-07-23 09:10

The [checked] is a selector that picks elements that are currently checked with the checked attribute not the property - in other words "if the element has the checked attribute, pick it up".

If you want to check if the checkbox is checked or not, you must use :checked.

Example usage:

if($('#test').is(':checked'))
{
   return true;
}

With jQuery 1.6 and higher you can use the .prop() function for performance reasons.

if($('#test').prop('checked'))
{
   return true;
}
查看更多
我只想做你的唯一
5楼-- · 2020-07-23 09:10

Because checked isn't an attribute of an input element. It is a property. Your *[checked] selector checks to see if it has the checked attribute, which would never exist on an element. You can add the checked="checked" to an input element which sets the checked property of that object, but that attribute will always be there even when unchecking the box. This is because checking and unchecking only changes the checked property of the checkbox, not the checked attribute.

查看更多
何必那么认真
6楼-- · 2020-07-23 09:11

check this http://jsfiddle.net/2QZvU/5/

it must be *[:checked]

As Matt said checked is a property not an attribute

查看更多
登录 后发表回答