The difference between attr method and prop method in jquery

Source: Internet
Author: User
Tags tagname

The checked most important concept about a property is that you have to remember that it has nothing to do with checked the state value, setting or setting the checked = "checked" checked = "true" property, and its state value true/false is irrelevant. , and the property value here, in fact, is only defaultChecked related to the state value, and can only be used to set checkbox the initial value. checkedthe value of the property does not change as the checkbox state changes, but checkbox the state value is. Therefore, in order to be able to better cross-browser compatibility, the determined checkbox checked state is to be processed using the state value.

For example:

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

These theories, for those dynamic properties, have the same effect, such as: selected and value attributes.

The attr () method sets or returns the property value of the selected element.

According to the different parameters of the method, the mode of operation also varies.

Returns the attribute value of the selected element.

The prop () method sets or returns the attributes and values of the selected element.

When the method is used to return a property value, the value of the first matching element is returned.

When the method is used to set property values, one or more property/value pairs are set for the matching element collection.

Note:the prop () method should be used to retrieve property values such as DOM properties (such as SelectedIndex, TagName, NodeName, NodeType, Ownerdocument, defaultchecked, and defaultselected).

Tip: If you want to retrieve HTML attributes, use the attr () method instead.

Tip: If you want to remove attributes, use the Removeprop () method.

jquery, the method used to get properties, mainly based on prop methods, we often use the attr method, but in the attr method, sometimes there are some problems, here is the jquery API to look at the attr introduction, Main content translated from the jquery API Description: attr ()

1. Basic Use Method

attr()Function: Gets a property value for the first element that matches to, or an attribute assignment for all matching elements.

Supported methods:

. attr (AttributeName)
    • Gets a property value that matches to the first element.
    • Input value AttributeName
    • Type:string, the name of the property you want to get

.attr()method, you can only get the value of the first element that matches to, and if you want to get the attribute values of all the elements that match, then you need to use the loop method in jquery, such as: .each() and .map() ;

Using jquery .attr() , getting the attribute value of an element has two of the most important benefits:

1: Simple to use, it can be used directly on a jquery object, and can continue to use other jquery methods after use.

2: Cross-browser compatibility, some of the properties of the method is not compatible with the browser, and even some in the same browser between different versions, there will be incompatible issues, the. attr () method reduces this incompatibility.

Note:A property value is one that typically returns a string, and occasionally returns a value that resembles a value or a numeric order. Note:In Ie6,ie7,ie8, if you try to change the Type property of an INPUT element, an error is thrown when the input is added to the page.

In jquery 1.6, the .attr() method queries those properties that are not set and returns a undefined. If you are going to restore or change the DOM state value, similar to, and checked selected so on, the state of disabled the form element, it is best to use the .prop() method.

Attribute value VS Status value

In some special cases, the difference between the attribute value and the state value is greatly affected. in the previous version of jquery 1.6 , the method would sometimes take the .attr() status value into account when recovering some properties, which would lead to browser compatibility issues. in jquery 1.6 , .prop() the method provided avoids recovering the status value, and the .attr() method restores the status value.

For example:,,,,,, selectedIndex tagName nodeName nodeType ownerDocument defaultChecked and defaultSelected These properties, you should use the .prop() method to restore the property value. In versions prior to JQuery 1.6 , these status values are available through .attr() acquisition, although obtaining these status values is not attr a working range. These state values and attributes are not associated with each other, they are just a state.

In terms of the properties of a Boolean logical type, if we define a DOM object such as HTML. <input type = "checkbox" checked = "checked" />, and assume that the HTML object is Javascript named in elem .

Take a look at the results of using different methods to checked value a property:

According to the specification, the “checked” attribute is a boolean-logical attribute, which means that if the attribute exists, then the value of the corresponding state value is correct, for example, even if the property has no value, or is set to an empty string, or set to “false” , is correct for boolean logical attributes.

However, the checked most important concept about a property is that you have to remember that it has nothing to do with checked the state value, setting or setting the property, checked = "checked" checked = "true" and its state value true/false is irrelevant. , and the property value here, in fact, is only defaultChecked related to the state value, and can only be used to set checkbox the initial value. checkedthe value of the property does not change as the checkbox state changes, but checkbox the state value is. Therefore, in order to be able to better cross-browser compatibility, the determined checkbox checked state is to be processed using the state value.

For example:

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

These theories, for those dynamic properties, have the same effect, such as: selected and value attributes.

Additional notes:

In the browser version prior to IE9, use the .prop() method to set DOM the state value of an element, which is different than the original value (number, String, or Boolean logical value), if the DOM element is not used to .removeProp() remove the state value before being removed from the document , then it will lead to memory leaks, if you want to more safely DOM set the value of the property above the object, without causing a memory leak, then use .data this sentence, do not understand

Example: The core code is as follows

1<body>2<input id= "Check1" type= "checkbox" checked= "Checked" >3<label for= "Check1" >check me</label>4<p></p>5<script>6$ ("Input" )7. Change (function() {8     var$input = $ ( This );9$ ("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 ();Ten</script>

View the original page code, you can click: Attr-prop;

Here is no longer an example attr of the normal use of the method, if you are interested, you can click to view: Example Demo

2: Use attr to assign a value operation. attr (Attributename,name)
    • Attributename:string, the property name that needs to be set
    • String or number, the property value of the property that needs to be set.
. attr (attributes)
    • Attributes:object, an object that needs to be set up as a property.
. attr (Attributename,function (index,attr))
    • Attributename:string, sets the property name.
    • function (index,attr): function,

The return value of the function is set to the value of the property, which this represents the currently selected element, the first parameter received is the sequence that represents the position in the currently selected element (starting at 0), the second parameter is the element, and the original property value for that property.

It .attr() is convenient to use the method to set the property value, especially if you need to set multiple properties, or if you need to set the value of a property to be a function return value, look at the following image label:

<img id="greatphoto" src="brush-seller.jpg" alt="brush seller"\>

Set a simple property, using the .attr() value of the ALT attribute that can be easily changed based on the property name and the property value.

$( "#greatphoto" ).attr( "alt", "Beijing Brush Seller" );

You can also use the same method to add a new property:

$( "#greatphoto" ).attr( "title", "Photo by Kelly Clark" );

You can also set multiple properties at once: Change the alt value of a property, and add a new property title .

$( “#greatphoto” ).attr({    alt: “Beijing Brush Seller”,    title: “photo by Kelly Clark”});

When setting multiple properties, the quotation marks of the property name can be omitted.

Warning:When you set the Class property, the quotation marks are not allowed to be omitted. Note:jquery prohibits change <input>And <button>Elements of typeproperty, if forced to change, under any browser, this throws an exception, this is because, in IE browser, typeThe property is not modifiable.so in all browsers, can not be set up, save compatibility of unity.

Computed Property values:

By using the function set property, you can perform a property assignment operation after the calculation by another property value, for example, a new property value based on an existing property join.

$( “#greatphoto” ).attr( “title”, function( i, val ) {    return val + ” – photo by Kelly Clark”;});

This function method of calculating attribute values is especially effective when setting different property values for multiple elements at once.

Example: Set some properties for all img In the page, the core code is as follows:

<Body><Img><Img><img>< div><b>attribute of Ajax</b></div ><script>$ (  "img"). attr ({src:  "/resources/hat.gif", Title: " jquery ", alt: " jquery Logo "}), $ (" div "). Text ($ ( Span class= "hljs-string" > "img"). attr ( "alt")); </script></ BODY>             
&AMP;LT;BR/&gt;

Based on the DIV's position in the page, set its ID property.


<Body><Div>zero-th<Span></Div><Div>first<Span></Span></Div><Div>second<Span></Span></div>< script>$ ( "div"). attr ( "id", function ( ARR) {return  "Div-id" + arr;}). each ( function () {$ (" span ", this). HTML (" (id = ' <b> "+ this.id +  "</b>");}); </script></ BODY>              
&AMP;LT;BR/&gt;

OK, here is a temporary description here, if you do not understand why .attr() the value and .prop() the value of the difference, then first look at the previous article, JS native operation HTML Object attribute differences, and then to see the jquery source, .attr() methods and .prop() method to achieve it.

http://www.zhangyunling.com/?p=38

The difference between attr method and prop method in jquery

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.