jQuery 1.6 之后应该使用.prop()判断多选框是否选中

jQuery 1.6 之后应该使用.prop()判断多选框是否选中

jQuery 1.6 之后应该使用.prop()判断多选框是否选中

prop()

Contents:

.prop( propertyName )Returns: String

Description: Get the value of a property for the first element in the set of matched elements.

  • version added: 1.6.prop( propertyName )

    propertyNameThe name of the property to get.

The .prop() method gets the property value for only the first element in the matched set. It returns undefined for the value of a property that has not been set, or if the matched set has no elements. To get the value for each element individually, use a looping construct such as jQuery’s .each() or .map() method.

The difference between attributes and properties can be important in specific situations.Before jQuery 1.6, the .attr() method sometimes took property values into account when retrieving some attributes, which could cause inconsistent behavior. As of jQuery 1.6, the.prop() method provides a way to explicitly retrieve property values, while .attr() retrieves attributes.

For example, selectedIndextagNamenodeNamenodeTypeownerDocument,defaultChecked, and defaultSelected should be retrieved and set with the .prop()method. Prior to jQuery 1.6, these properties were retrievable with the .attr() method, but this was not within the scope of attr. These do not have corresponding attributes and are only properties.

Concerning boolean attributes, consider a DOM element defined by the HTML markup <input type="checkbox" checked="checked" />, and assume it is in a JavaScript variable namedelem:

elem.checked true (Boolean) Will change with checkbox state
$(elem).prop("checked") true (Boolean) Will change with checkbox state
elem.getAttribute("checked") "checked" (String) Initial state of the checkbox; does not change
$(elem).attr("checked")(1.6) "checked" (String) Initial state of the checkbox; does not change
$(elem).attr("checked")(1.6.1+) "checked" (String) Will change with checkbox state
$(elem).attr("checked")(pre-1.6) true (Boolean) Changed with checkbox state

According to the W3C forms specification, the checked attribute is a boolean attribute, which means the corresponding property is true if the attribute is present at all—even if, for example, the attribute has no value or an empty string value. The preferred cross-browser-compatible way to determine if a checkbox is checked is to check for a “truthy” value on the element’s property using one of the following:

  • if ( elem.checked )
  • if ( $(elem).prop("checked") )
  • if ( $(elem).is(":checked") )

If using jQuery 1.6, the code if ( $(elem).attr("checked") ) will retrieve the actual content attribute, which does not change as the checkbox is checked and unchecked. It is meant only to store the default or initial value of the checked property. To maintain backwards compatability, the .attr() method in jQuery 1.6.1+ will retrieve and update the property for you so no code for boolean attributes is required to be changed to .prop(). Nevertheless, the preferred way to retrieve a checked value is with one of the options listed above. To see how this works in the latest jQuery, check/uncheck the checkbox in the example below.

Additional Notes:

  • In Internet Explorer prior to version 9, using .prop() to set a DOM element property to anything other than a simple primitive value (number, string, or boolean) can cause memory leaks if the property is not removed (using .removeProp()) before the DOM element is removed from the document. To safely set values on DOM objects without memory leaks, use.data().

Example:

Display the checked property and attribute of a checkbox as it changes.

<!DOCTYPE html>
<html>
<head>
  <style>
  p { margin: 20px 0 0 }
  b { color: blue; }
</style>
  <script src="http://code.jquery.com/jquery-latest.js"></script>
</head>
<body>
  
<input id="check1" type="checkbox" checked="checked">
<label for="check1">Check me</label>
<p></p>

<script>
$("input").change(function() {
  var $input = $(this);
  $("p").html(".attr('checked'): <b>" + $input.attr('checked') + "</b><br>"
              + ".prop('checked'): <b>" + $input.prop('checked') + "</b><br>"
              + ".is(':checked'): <b>" + $input.is(':checked') ) + "</b>";
}).change();
</script>

</body>
</html>

Demo:

.prop( propertyName, value )Returns: jQuery

Description: Set one or more properties for the set of matched elements.

  • version added: 1.6.prop( propertyName, value )

    propertyNameThe name of the property to set.

    valueA value to set for the property.

  • version added: 1.6.prop( map )

    mapA map of property-value pairs to set.

  • version added: 1.6.prop( propertyName, function(index, oldPropertyValue) )

    propertyNameThe name of the property to set.

    function(index, oldPropertyValue)A function returning the value to set. Receives the index position of the element in the set and the old property value as arguments. Within the function, the keyword this refers to the current element.

The .prop() method is a convenient way to set the value of properties—especially when setting multiple properties, using values returned by a function, or setting values on multiple elements at once. It should be used when setting selectedIndextagNamenodeName,nodeTypeownerDocumentdefaultChecked, or defaultSelected. Since jQuery 1.6, these properties can no longer be set with the .attr() method. They do not have corresponding attributes and are only properties.

Properties generally affect the dynamic state of a DOM element without changing the serialized HTML attribute. Examples include the value property of input elements, the disabledproperty of inputs and buttons, or the checked property of a checkbox. The .prop() method should be used to set disabled and checked instead of the .attr() method. The .val()method should be used for getting and setting value.

$("input").prop("disabled", false);
$("input").prop("checked", true);
$("input").val("someValue");

Important: the .removeProp() method should not be used to set these properties to false. Once a native property is removed, it cannot be added again. See .removeProp() for more information.

Computed property values

By using a function to set properties, you can compute the value based on other properties of the element. For example, to toggle all checkboxes based off their individual values:

$("input[type='checkbox']").prop("checked", function( i, val ) {
  return !val;
});

Note: If nothing is returned in the setter function (ie. function(index, prop){}), or ifundefined is returned, the current value is not changed. This is useful for selectively setting values only when certain criteria are met.

Additional Notes:

  • In Internet Explorer prior to version 9, using .prop() to set a DOM element property to anything other than a simple primitive value (number, string, or boolean) can cause memory leaks if the property is not removed (using .removeProp()) before the DOM element is removed from the document. To safely set values on DOM objects without memory leaks, use.data().

Example:

Disable all checkboxes on the page.

<!DOCTYPE html>
<html>
<head>
  <style>
  img { padding:10px; }
  div { color:red; font-size:24px; }
</style>
  <script src="http://code.jquery.com/jquery-latest.js"></script>
</head>
<body>
  
  <input type="checkbox" checked="checked" />
  <input type="checkbox" />
  <input type="checkbox" />
  <input type="checkbox"  checked="checked" />

<script>
$("input[type='checkbox']").prop({
  disabled: true
});
</script>

</body>
</html>

Demo:

Support and Contributions

Need help with .prop() or have a question about it? Visit the jQuery Forum or the #jquery channel onirc.freenode.net.

Think you’ve discovered a jQuery bug related to .prop()Report it to the jQuery core team.

Found a problem with this documentation? Report it on the GitHub issue tracker

发表评论

电子邮件地址不会被公开。 必填项已用*标注