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

2020-07-23 08:39发布

问题:

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

回答1:

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;
}


回答2:

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.



回答3:

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.



回答4:

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

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



回答5:

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

it must be *[:checked]

As Matt said checked is a property not an attribute