jquery Source parsing: jquery action on element attributes 1

Source: Internet
Author: User

Let's take a look at how many of the methods in jquery are used to manipulate element properties.

First, consider the example method:

Then, look at the static method (tool method):

Static method is used internally, we use very little outside, the instance method is external.

Next, let's see how some of these methods are used.

$ ("#div1"). attr ("title", "Hello"), set property, two parameters.

$ ("#div1"). attr ("title"), gets the property value, when one parameter.

$ ("#div1"). Prop ("title"), you can also get this property value.

The difference between them is that attr is equivalent to native setattribute (), getattribute ().

Prop is equivalent to a native. Property name ([property name]), such as: Div.title = "Hello";d iv.title.

Here is a simple way to tell the difference between native:

$ ("#div1"). attr ("Chaojidan", "Hello"), adds a property named Chaojidan to the element. The Chaojidan attribute is displayed on the element div tag.

$ ("#div1"). Prop ("Chaojidan", "Hello"), also adds a property named Chaojidan to the element, but does not display this property on the element div tag.

Because Chaojidan is a custom property, it is not an intrinsic property of an element.

There is one more difference:

<div chaojidan= "Hello" id= "Div1" >

$ ("#div1"). attr ("Chaojidan") returns hello. But $ ("#div1"). Prop ("Chaojidan"), in some browsers, will return empty. Because Chaojidan is a custom attribute.

There is one more difference:

For the href attribute of the A tag, attr returns the property value of the href, but prop returns the document. The property value of the URL + href. The href is the intrinsic property of the a tag.

For more specific differences, see: http://www.cnblogs.com/chaojidan/p/4108777.html

Intrinsic properties, if you delete with Removeprop, there will be problems, for example, delete an element ID, is deleted. But with removeattr, you can. Therefore, PRP and removeprop use less, while attr and removeattr used more.

Finally, let's look at the source code:

JQuery.fn.extend ({
Attr:function (name, value) {
Return jquery.access (this, jquery.attr, name, value, Arguments.length > 1); //This method has been mentioned before, if Arguments.length > 1, it represents the set operation, if False, then it represents a get operation. The callback method that is actually called is a static method: Jquery.attr. Name is the property name you passed in, and value is the attribute you passed in.
},

Removeattr:function (name) {
Return This.each (function () {
Jquery.removeattr (this, name); The //instance method Removeattr, called is also the same name as the static method Removeattr.
});
},

Prop:function (name, value) { ///is also a static method Jquery.prop
Return jquery.access (this, jquery.prop, name, value, Arguments.length > 1);
},

Removeprop:function (name) {
Return This.each (function () {
Delete this[jquery.propfix[name] | | name]; //Delete attribute, if the property name needs to be compatible, do it, for example: class to become classname.
});
},

......

});

Jquery.extend ({

Attr:function (elem, name, value) {
var hooks, ret,
NType = Elem.nodetype;

if (!elem | | nType = = 3 | | nType = = 8 | | nType = = 2) { //element not present or text node, or comment node, or attribute node, cannot set property, return directly. ELEMENT nodes to set properties.
Return
}

if (typeof Elem.getattribute = = = core_strundefined) { //core_strundefined = "undefined". Document,window does not have a getattribute method, so the prop method is used, and the prop method is in the form of a. Property name.
Return Jquery.prop (elem, name, value);
}

if (nType!== 1 | |!jquery.isxmldoc (elem)) { //If it is not an element node or an element node is not under an XML document, then Jquery.isxmldoc (elem) returns True if it is. This means that if it is an element node under an XML document, it will not be entered into the IF statement. The elements under the XML document are all custom, with no compatibility issues. Therefore, you do not need to enter the IF statement for compatibility processing. The element node under the HTML document has compatibility issues, so it needs to be handled.

Name = Name.tolowercase ();

      Hooks is specifically designed to address compatibility issues in jquery. Support is used to detect browser compatibility, hooks to solve compatibility problems, hooks for different types have corresponding hooks, such as: attr, corresponds to Attrhooks. There are two kinds of hooks, one is the compatibility processing for setting, the set method, one is for obtaining the compatibility processing, the Get method. If there is a compatibility problem, the Set method or Get method returns the value after compatibility processing, and if there is no compatibility problem, SET returns UNDEFINED,GET and returns NULL. You can look at the Attrhooks object, in fact, pass the property name in, only the Type property has compatibility problem. There is no compatibility issue with the get operation only for setup operations. The specific point is: Set the type = "Radio" compatibility issue.

hooks = jquery.attrhooks[Name] | |   JQuery.expr.match.bool.test (name) boolhook:nodehook)   // jquery.expr = Sizzle.selectors,sizzle.selectors object has the match:matchexpr attribute. Matchexpr is also an object in which the bool attribute value is: New RegExp ("^ (?:" + Booleans + ") $", "I"). and Booleans = "checked|selected|async|autofocus|autoplay|controls|defer|disabled|hidden|ismap|loop|multiple|open| Readonly|required|scoped ". Nodehook = undefined. If the type is not set to radio under IE, then the name will be judged to match this regular. If it matches, it returns Boolhook, and the mismatch returns undefined. Boolhook is used to specifically handle bool type properties. For example: <input type= "checkbox" checked= "Checked", $ ("input"). attr ("Checked"): checked,$ ("input"). Prop ("checked") : True. The Checked property belongs to the bool Type property. For the above example, we know that the value of attr gets checked is checked, because when we set it should also be $ ("input"). attr ("Checked", "checked"), but some people may not be familiar with jquery, will write $ (" Input "). attr (" Checked ", true), then this writing line can not, is also possible, because jqueyr inside to do a compatible treatment. Actually is Boolhook object, everybody can see this object at the end of the article, see how it is handled.

}

if (value!== undefined) { //set Operation

if (value = = = null) { //$ ("#div1"). attr ("Chaojidan", null) in this case, the properties of the Chaojidan are removed.
Jquery.removeattr (elem, name);

} else if (hooks && "set" in hooks && (ret = Hooks.set (elem, value, name))!== undefined) {
return ret; //If there is a compatibility problem, process it and return the processed value.

} else {
Elem.setattribute (name, Value + ""); //Use the normal way to set the operation. Because the property value is a string, the number is converted to a string.
return value;
}

} else if (hooks && "get" in hooks && (ret = Hooks.get (elem, name))!== null) {
return ret; //Get operation. See if there is a compatibility operation for get.

} else {
ret = jQuery.find.attr (elem, name); //jquery.find = Sizzle. The attr method in sizzle is used to deal with the compatibility of getattribute method.

return ret = = null? Undefined:ret;
}
},

Attrhooks: {
Type: {
Set:function (Elem, value) { //This method solves such a problem: input = document.createelement ("input"); Input.value = "T"; Input.typ E = "Radio"; support.radiovalue = Input.value = = = "T"; When you assign a value to the value of input and then set the type of input to radio, the value of input under IE becomes on, and other browsers will get T.

if (!jquery.support.radiovalue && value = = = "Radio" && Jquery.nodename (elem, "input")) { //if the above compatibility problem exists, that is, JQuery.support.radioValue =false,ie is False,value is you set the value of the Type property, and the element is input, This means: You set the Type=radio action on the INPUT element.
var val = elem.value; How to solve this compatibility problem under IE, we first save the value of this input. After setting the type = "Radio", the value is then assigned to the past. So that the value of its input will not become on.
elem.setattribute ("type", value);
if (val) {
elem.value = val;
}
return value;
}
}
}
},

Removeattr:function (Elem, value) {
var name, propname,
i = 0,
Attrnames = value && value.match (core_rnotwhite); //core_rnotwhite =/\s+/g, which means that you can delete multiple property values at the same time, such as $ ("div"). Removeattr ("ID name class"), value = "id Name class", Calling the match method and passing in the regular/\s+/g returns [Id,name,class].

if (attrnames && elem.nodetype = = 1) { //Must be element node elements
while ((name = attrnames[i++])) {
propname = jquery.propfix[Name] | | name;  // propfix: {"for": "Htmlfor", "Class": "ClassName"}, If the property name you want to delete is for or class, then you need to do a compatible processing. So when you do $ ("div"). Removeattr ("class") operation, there is no problem.

if (jQuery.expr.match.bool.test (name)) { //If the property name to be removed is of type bool (that is, its value is obtained by [property name], is false or True)
elem[propname] = false; //You need to assign the attribute value of this bool type to FALSE, because this property has been removed and should not be obtained with [property name] to return true. For example: The Checked property of the input element, when you remove the checked attribute, you get true by input.checked, then you will be considered to have this checked in input , And then checked you have removed, so you must set its input.checked=false. For details, see here: http://www.cnblogs.com/chaojidan/p/4108777.html

}

Elem.removeattribute (name); //Call native method to remove
}
}
},

Prop:function (elem, name, value) {
var ret, hooks, notxml,
NType = Elem.nodetype;

if (!elem | | nType = = 3 | | nType = = 8 | | nType = = 2) {
Return
}

Notxml = NType!== 1 | | !jquery.isxmldoc (Elem);

if (notxml) {   //is not an XML document, Compatibility handling required
name = jquery.propfix[Name] | | name; //propfix has already spoken of
hooks = jquery.prophooks[name];  //If name is TabIndex, compatibility processing is required. TabIndex can toggle the order of the Cursors (via tab), and switch from small to large by the size of the TabIndex attribute value in the element (...).
}

if (value!== undefined) { //set Operation
Return hooks && "set" in hooks && (ret = Hooks.set (elem, value, name))!== undefined?  RET: (elem[name] = value); //If the return is elem[name] = value, it is actually return value.

} else { //Get Operation
return hooks && "get" in hooks && (ret = Hooks.get (elem, name))!== null? ret:elem[name];
}
}, 

Prophooks: {
TabIndex: {   //This property is a compatibility issue when acquired. In fact, when the element does not support the TabIndex property by default and does not explicitly set its TabIndex property, IE6-8 returns 0, and 1 is returned under the standard browser. So compatible processing, all returns -1.
Get:function (elem) {
return Elem.hasattribute ("TabIndex") | | Rfocusable.test (elem.nodename) | | Elem.href?  elem.tabindex: -1;    //rfocusable =/^ (?: Input|select|textarea|button) $/i; If the element does not belong to these elements specified in the regular, and the element does not have an href attribute, then it proves that this element does not support the TabIndex property by default.     
}

......
});

Boolhook = {
set:function (Elem, value, name) { //According to the example, suppose you set $ ("input"). attr ("Checked", true)
if (value = = = False) { //value equals True. If it is $ ("input"). attr ("checked", false) removes the Checked property.
jquery.removeattr (elem, name);
} else {
Elem.setattribute (name, name); //$ ("input"). attr ("Checked", "checked")
}
return name;
}
};

If (!jquery.support.optselected) { //The hooks here is whether the first OPTION element for the SELECT element will be selected by default.
jQuery.propHooks.selected = { //under IE (Old Safari) is not selected by default, so the selected value of option is returned false, while other browsers return true.
get:function (elem) { //Only get method, because this problem occurs only when fetching. Suppose you want to get the selected property value for option.
var parent = Elem.parentnode;
if (parent && parent.parentnode) {
Parent.parentNode.selectedIndex; you can set option.selected = True if you first access the Select.selectedindex property when you get the value of the selected of option. This means that when you access the selected property of option, you first access the SelectedIndex property of its parent select element, forcing the browser to calculate the option's Selected property to get the correct value. It is important to note that the parent element of the option element is not necessarily a select, or it may be optgroup. Here is the support for ie9+, so option parentnode is Optgroup,optgroup parentnode is select.
}
return null;
}
};
}

Jquery.each ([ ///Do not understand each method, you can go here to see the http://www.cnblogs.com/chaojidan/p/4156600.html
"TabIndex",
"ReadOnly",
"MaxLength",
"cellspacing",
"cellpadding",
"RowSpan",
"ColSpan",
"Usemap",
"frameborder",
"Contenteditable"
], function () {
jquery.propfix[this.tolowercase ()] = this; //This is the option in the array, such as: jquery.propfix[tabindex.tolowercase ()] = TabIndex; This is done in case someone does the JQuery property operation, The name is written in the case of all lowercase, here to do the next compatibility, so that the user input is all lowercase attribute name, also can operate normally.
});

This lesson, is still more important, involves a lot of things, want to thoroughly understand, still need a certain foundation.

Come on!

jquery Source parsing: jquery action on element attributes 1

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.