In jquery, attr () and prop () use examples (with different usages) _jquery

Source: Internet
Author: User
Tags tagname

This example describes the use of attr () and prop () functions in jquery. Share to everyone for your reference, specific as follows:

attr () Method of jquery

jquery uses the attr () method to get and set element attributes, attr is the abbreviation for attribute (attributes), often used in jquery DOM operations attr (), attr () has 4 expressions.

1. attr (property name)//Get the value of the property (get the property value of the first matching element). This method makes it easy to get the value of a property from the first matching element. Returns undefined if the element has no corresponding property

2. attr (property name, property value)//Set the value of the property (set a property value for all matching elements). )

3. attr (property name, function value)//Set the function value of the property (set a computed property value for all matching elements). Instead of providing a value, a function is provided that evaluates the value of the function as the property value. )

4.attr (properties)//Set multiple attribute values to the specified element, that is: {property name one: "Property value One", property name Two: "Property value Two", ...}. (This is the best way to set many properties in batches in all matching elements.) Note that if you want to set the class attribute of an object, you must use ' className ' as the property name. Or you can use ' class ' or ' id ' directly. )

Sample code:

<! DOCTYPE HTML PUBLIC "-//W3C//DTD XHTML 1.0 transitional//en"
"http://www.w3.org/TR/xhtml1/DTD/ Xhtml1-transitional.dtd ">
 
 

1.ATTR (name)//Get the value of the property

1.1 Use attr (name) to get the title value:

<script>
Alert ($ ("ul Li:eq (1)"). attr ("title"));
</script>

Results:

1.2 Use attr (name) to get the ALT value:

<script>
Alert ($ ("ul Li:eq (1)"). attr ("alt"));
</script>

Results:

2. attr (Name,value)//Set the value of the property

2.1 Use attr (Name,value) to modify the title value is: Do not eat oranges

<script>
$ ("ul Li:eq (1)"). attr ("title", "Do not eat oranges");
Alert ($ ("ul Li:eq (1)"). attr ("title"));
</script>

Results:

3. attr (NAME,FN)//Set the function value of the property

3.1 Set the value of the Alt property to the value of the title property.

<script>
$ ("ul Li:eq (1)"). attr ("title", function () {return this.alt});
Alert ($ ("ul Li:eq (1)"). attr ("title"));
</script>

Results:

4.attr (properties)//Set an object in the form of "name/value" to the property of all matching elements

4.1 Get <ul> 2nd <li> set title and Alt properties.

<script>
$ ("ul Li:eq (1)"). attr ({title: "Do not drink orange juice", alt: "Not 123"});
Alert ($ ("ul Li:eq (1)"). attr ("title"));
Alert ($ ("ul Li:eq (1)"). attr ("alt"));
</script>

Results:

4.2 Get <ul> 2nd <li> set class.

<script>
$ ("ul Li:eq (1)"). attr ({className: "Lili"});
</script>

Results:

4.3 Get <ul> 2nd <li> set ID.

<script>
$ ("ul Li:eq (1)"). attr ({ID: "Lili"});
</script>

Results:

4.4 Get <ul> 2nd <li> set style.

<script>
$ ("ul Li:eq (1)"). attr ({style: "color:red"});
</script>

Results:

Adding Alt to Li is an error that can only be used in IMG, area, and input elements (including applet elements). For the INPUT element, the ALT attribute is intended to replace the picture of the Submit button. In order to explain the attr () method in detail here, there is no suitable attribute, all ALT is used for example, only for learning reference attr () method usage.

Here is a description of the difference between Alt and Tite.

ALT: This is the text that describes the graphic, and when the picture cannot be displayed, the text is displayed instead of the picture. The text will also appear when you move the mouse over the picture.
Title: After the mouse is put up, will display the text.

So how do you delete attributes?

The key word for deleting attributes in jquery is: removeattr Note that a is uppercase. See how it's used:
The same is the HTML code in the usage one, I want to delete Li's title attribute, so that's it:

<script>
$ ("ul Li:eq (1)"). Removeattr ("title");
</script>

So simple, attr in fact is the original JS getattribute simplification, and removeattr is the removeattribute of the shorthand.

So is there a property similar to attr ()?

The Val () in jquery is similar ,
$ (this). Val (); Gets the value of an element node, equivalent to $ (this). attr ("value");
$ (this). Val (value); Set the value value of an element node, equivalent to $ (this). attr ("value", value);

Two, jquery prop () method:

The prop () function is used to set or return the property values of the elements that the current jquery object matches.

This function belongs to the jquery object (instance). If you need to remove the properties of a DOM element, use the Removeprop () function.

Grammar

JQuery 1.6 adds this function. The prop () function has the following two uses:

Usage One:

Jqueryobject.prop (PropertyName [, value])
Sets or returns the value of the specified property propertyname. If the value parameter is specified, it indicates that the values for setting the property PropertyName are valued, and if the value parameter is not specified, the value of the property PropertyName is returned.

The parameter value can also be a function, and prop () will traverse the function based on all matching elements, and the this pointer in the function will point to the corresponding DOM element. Prop () also passes two arguments to the function: The first argument is the index of the element in the matching element, and the second parameter is the current value of the element's PropertyName property. The return value of a function is the value set for the PropertyName property of the element.

Usage Two:

Jqueryobject.prop (object)
Sets the value of any number of properties at the same time as an object. Each property of Object objects corresponds to PropertyName, and the values of the properties correspond to value.

Note: All the Set property actions of the prop () function are for each element that matches the current jquery object; All read property actions are for only the first matching element.
parameters

Find the corresponding argument based on the parameter name defined in the previous syntax section.

Parameters Description
PropertyName The name of the property specified by the string type .
Value An optional/object/function type Specifies a property value, or a function that returns a property value.
Object object that encapsulates multiple key-value pairs while setting multiple properties.
Parameter value can be any type, including objects and arrays.

return value

The return value of the prop () function is any type, and the type of the return value depends on whether the current prop () function performs the Set property action or the Read property action.

If the prop () function performs the Set property action, the current jquery object itself is returned, and the property value that is read is returned if it is a read property operation.

If the current jquery object matches more than one element, the prop () function takes only the first matching element when the property value is returned. Returns undefined if the element does not have a specified property.

The main difference between prop () and attr () is that the prop () function is for the properties of the DOM element (the JS element object), and the attr () function is for the properties of the document node corresponding to the DOM element. See the difference between the jquery function attr () and prop () for details.

Attention matters

1. If you change the Type property of the <input> and <button> elements through the prop () function, an error will be thrown in most browsers because the property is generally not allowed to change later.

2. If you use the Prop () function to manipulate the properties of the checked, selected, disabled, and so on of the form element, return True if the element is selected (or disabled), otherwise (meaning that the attribute is not in HTML) returns false.

3. The prop () function can also set or return certain properties on the element object of the DOM elements, for example: TagName, SelectedIndex, NodeName, NodeType, Ownerdocument, Properties such as defaultchecked and defaultselected.

4. In IE9 and earlier versions, if the property value set using the Prop () function was not a simple raw value (String, number, Boolean), and the property was not removed before the corresponding DOM element was destroyed, it could cause a memory leak problem. If you are just trying to store data, it is recommended that you use data () functions to avoid memory leaks.

Example & Description

Take the following HTML code as an example:

<div id= "N1" >
  <p id= "n2" class= "demo test" data-key= "UUID" data_value= "1235456465" >codeplayer</p >
  <input id= "n3" Name= "order_id" type= "checkbox" value= "1" >
  <input id= "N4" name= "order_id" type= " CheckBox "checked=" Checked "value=" 2 ">
</div>

We write the following jquery code:

var $n 2 = $ ("#n2"); The prop () action is for attributes of elements (element objects), not attributes of ELEMENT nodes (HTML documents) Document.writeln ($n 2.prop ("Data-key")); Undefined Document.writeln ($n 2.prop ("Data_value")); Undefined Document.writeln ($n 2.prop ("id")); N2 Document.writeln ($n 2.prop ("TagName")); P Document.writeln ($n 2.prop ("ClassName")); Demo Test Document.writeln ($n 2.prop ("InnerHTML")); Codeplayer Document.writeln (typeof $n 2.prop ("getattribute"));
The properties of the function//prop () setting are also for elements (element objects), and therefore can also be accessed directly through the element itself $n 2.prop ("prop_a", "Codeplayer"); Document.writeln ($n 2[0].prop_a);
Codeplayer var n2 = document.getElementById ("n2"); Document.writeln (n2.prop_a); Codeplayer//Set multiple properties at the same time as an object, the property value can be an object, an array, and any type $n 2.prop ({prop_b: "Baike", Prop_c:18, site: {name: "Codeplayer"
, url: "http://www.jb51.net/"}); Document.writeln ($n 2[0].prop_c); Document.writeln ($n 2[0].site.url); http://www.jb51.net///Select all check boxes (unchecked instead, select to uncheck) $ ("Input:checkbox"). Prop ("Checked", function (index, oldValue) {return!oldvalue;});

 

Attachment: The difference between attr and prop in jquery

When should the prop be used when the Prop method is introduced into the high version of jquery? When do you use attr? What's the difference between two of them? These problems have arisen.

There are a lot of answers on the web about their two differences. Here to talk about my experience, my experience is very simple:

For the intrinsic properties of the HTML element itself, the prop method is used when processing.
For our own custom DOM attributes for HTML elements, the attr method is used when processing.

The above description may be a little vague, just for a few examples to know.

<a href= "http://www.baidu.com" target= "_self" class= "BTN" > Baidu </a>

In this example, the DOM attribute of the <a> element has "href, target, and class", which are attributes of the <a> element itself, and attributes that are included in the standards of the consortium, or that can be intelligently prompted in the IDE, These are called intrinsic attributes. It is recommended that you use the Prop method when handling these properties.

<a href= "#" id= "Link1" action= "delete" > Delete </a>

In this example, the DOM attribute of the <a> element has "href, id, and action", and it is obvious that the first two are intrinsic attributes, and that the next "action" attribute is our own custom,<a> element itself does not have this attribute. This is a custom DOM property. It is recommended that you use the Attr method when handling these properties. When you use the Prop method to take values and set property values, the undefined value is returned.

Let me cite one more example:

<input id= "Chk1" type= "checkbox"/> is visible
<input id= "Chk2" type= "checkbox" checked= "Checked"/> is visible

Elements, such as Checkbox,radio and select, select Attributes that correspond to "checked" and "selected", which are also intrinsic properties, and therefore need to be manipulated using the prop method to get the correct results.

$ ("#chk1"). Prop ("checked") = = False
$ ("#chk2"). Prop ("checked") = = True

If the attr method is used above, it will appear:

$ ("#chk1"). attr ("checked") = = undefined
$ ("#chk2"). attr ("checked") = = "Checked"

I hope this article will help you with the jquery program design.

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.