JQuery discussion (6) jQuery discussion (5)

Source: Internet
Author: User

Last article: jQuery discussion (V). Today we will analyze removeClass (), removeProp (), toggleClass (), and val ().

RemoveClass ():
/*** The internal implementation of the removeClass method is similar to that of the addClass method. Both methods first determine the parameter type: * If the parameter is of the Function type, the Function is used. call () executes the function parameter, obtains the returned value, and then * uses jQuery. the each method and the removeClass method execute commands on each matching element. * The parameter is of the String type. First, the String value rules for the class attribute of each matching element are in the form of * "class1 class2 class3, then perform respective processing (remove or add) */removeClass: function (value) {var removes, className, elem, c, cl, I, l; // if the parameter is of the Function type, run the branch statement if (jQuery. isFunction (value) {// The each method is often used in jQuery because There are often multiple jQuery objects. this method allows each jQuery object to execute the corresponding operation return this. each (function (j) {/* Function is used here. call (), which is often used in jQuery internal implementation and functions like this. apply (). Both are used to change the running context and use an existing method to perform operations. The difference is that the parameter passing method. value here. call (this, j, this. className) returns one or more removed class names separated by Spaces */jQuery (this ). removeClass (value. call (this, j, this. className);}/** only when the parameter is String or does not exist (or the parameter can be equal to undefined ), when the parameter does not exist (or the parameter is equal to undefined, all style class names of the matching element will be removed */if (value & typeof value = "string") | value = undefined) {/// core_rspace =/\ s +/, used to match one or more blank characters removes = (val Ue | ""). split (core_rspace); // separate the provided parameters by blank characters and put them in an array. // process each item of the matching element cyclically (I = 0, l = this. length; I <l; I ++) {elem = this [I]; // this indicates a set of matched elements, this [I] indicates each matched item. // ensure that the element is an element node and the class attribute of the element exists if (elem. nodeType = 1 & elem. className) {// adding a blank character before and after the original class name string of the element ensures that the new class name is not connected to the original class name after it is added, this causes the error className = ("" + elem. className + ""). replace (rclass, ""); for (c = 0, cl = remo Ves. length; c <cl; c ++) {// ensure that the newly added className does not exist in the class attribute of the original element while (className. indexOf ("" + removes [c] + "")> = 0) {// The Name Of The style class to be replaced is first processed as "class1, then replace it with "" className = className. replace ("" + removes [c] + "", "") ;}}/** jQuery. the trim method is used to remove spaces before and after the String. If the parameter does not exist, all style classes of the matching element will be removed, so it is directly equal to "". If the parameter exists and is of the String type, remove spaces before and after the style class name */elem. className = value? JQuery. trim (className): "" ;}}/// form a chain call return this ;}

This method is used to remove one, multiple, or all class attributes of each matching element. If a style class name is used as a parameter, only such a style class is deleted as a matched element set. If no style name is used as a parameter, all style classes will be removed. Usage:

  • RemoveClass ([className])

    ClassNameName of the style attribute removed for each matching element.

  • RemoveClass (function (index, class ))

    Function (index, class)This function returns one or more removed style names separated by spaces. The index location of the received element and the old style name of the element are used as parameters.

  

RemoveProp ():
/* Propfix: {tabindex: "tabindex", readonly: "readonly", "for": "htmlfor", "class": "classname", maxlength: "maxlength", cellspacing: "cellspacing", cellpadding: "cellpadding", rowspan: "rowspan", colspan: "colspan", usemap: "usemap", frameborder: "frameborder ", contenteditable: "contenteditable"}, which is used to correct IE6, 7 getattribute, setattribute, removeattribute, and other methods in IE browser */removeprop: function (name ){ Name = jquery. propfix [name] | Name; return this. each (function () {// try/catch is used to process the extraction in IE browser (for example, removing the attribute of a window) try {/* Here This refers to a matching element. We can use this [name] to access the name attribute of the element object. There are two ways to access the attributes of the object, the dot operator or the brackets operator. However, we recommend that you use the brackets operator, because the brackets operator is still valid in the following two cases: dynamically set attributes; Attribute names are not valid variable names (for example, attribute names contain spaces, or the attribute name is a JS keyword) */This [name] = undefined; // set the name attribute to undefined Delete this [name]; // Delete is the property used to remove objects} catch (e ){}});}

This method is used to delete the attribute set for the matching element. Only one parameter is accepted: removeProp (propertyName ).PropertyNameParameter indicates the name of the property to be removed. This method will remove.prop()Attribute set by the method. If you try to remove the DOM element orwindowSome built-in property attributes on the object may cause errors in the browser. If soJQuerySet the propertyundefinedAnd then ignore any browser errors. In general, you only need to remove custom property attributes, rather than the built-in (native) property attributes.

Note:Do not use this method to remove native property attributes, such as checked, disabled, or selected. This will completely remove this property. Once they are deleted, they cannot be added. Please use.prop() To set these property valuesfalse.

Note:
  • Before IE 9, use .prop() When assigning values to attributes of a DOM element, if the assigned type is not a basic type (number, string, or boolean ),.removeProp()Method Before the DOM element is removed from the document. To safely assign values to DOM objects without worrying about memory leaks, use.data()Method.

 

ToggleClass ():
ToggleClass: function (value, stateVal) {var type = typeof value, // The type of the first parameter isBool = typeof stateVal = "boolean "; // determine whether the second parameter is boolean. // if the first parameter is of the Function type, run the if (jQuery. isFunction (value) {// The each method is often used in jQuery, because the jQuery objects we operate on are often multiple, this method allows each jQuery object to execute the corresponding operation return this. each (function (I) {/* Function is used here. call (), which is often used in jQuery internal implementation and functions like this. apply (). Both are used to change the running context and use an existing method to perform operations. The difference is that the parameter passing method. value here. call (this, j, this. className, stateVal) returns the name of the style class to be switched on each element in the matched element set */jQuery (this ). toggleClass (value. call (this, I, this. className, stateVal), stateVal);} // The each method is often used in jQuery, because we usually operate on multiple jQuery objects, this method allows each jQuery object to execute the corresponding operation return this. each (function () {// if the first parameter is of the String type, run if (type = "string") {var className, I = 0, self = jQuery (th Is), state = stateVal, classNames = value. split (core_rspace); while (className = classNames [I ++]) {// judge the attribute values of each class and decide whether to add or remove state = isBool? State :! Self. hasClass (className); self [state? "AddClass": "removeClass"] (className) ;}} else if (type = "undefined" | type = "boolean") {if (this. className) {// if the class attribute exists, save jQuery. _ data (this, "_ className _", this. className);} // switch the entire class attribute, that is, return the string after adding or deleting the class value to the class attribute of each matching element. this. className = this. className | value = false? "": JQuery. _ data (this, "_ className _") | "";}});}

This method adds or deletes one or more style classes on each element of the matched element set, depending on whether the style class exists or the value is switched to the attribute. That is, if there is (does not exist), delete (ADD) a class.

  • ToggleClass (className)

    ClassNameOne or more style class names used to switch between each element in the matched element set (separated by spaces.

  • ToggleClass (className, switch)

    ClassNameOne or more style class names used to switch between each element in the matched element set (separated by spaces.

    SwitchA boolean value used to determine whether to add or remove a style class.

  • ToggleClass (function (index, class), [switch])

    Function (index, Class)Returns a function of the style class name to be switched on each element in the matched element set. The index position of the received element and the old style class of the element are used as parameters.

    SwitchA boolean value used to determine whether to add or remove a style class. If the value of this parameter istrue, The style class will be added; if the value of this parameter isfalse, The style class will be removed.

 

Val ():
Val: function (value) {var hooks, ret, isFunction, elem = this [0]; // match the first element of the element // If the parameter does not exist, execute this branch statement if (! Arguments. length) {// ensure that the first element of the matching element has the if (elem) {/* jQuery val () function, which must be processed differently for different labels, therefore, define a function ing table valHooks: {option: {get: function () {}}} using tagName as the key. In this way, you do not need to write: if (elm. tagName = 'option') {return ...;} Else if (elm. tagName = 'textarea ') {return ...;} Can be processed in a unified manner: valHooks [elm. tagName. toLowerCase ()]; ing tables manage functions as common data and are widely used in dynamic languages. * // hooks is used to solve the browser compatibility problem (select, option, and other elements) hooks = jQuery. valHooks [elem. type] | jQuery. valHooks [elem. nodeName. toLowerCase ()]; if (hooks & "get" in hooks & (ret = hooks. get (elem, "value "))! = Undefined) {return ret; // ret is the obtained value} ret = elem. value; // directly obtain the value of an element. In this case, the return typeof ret = "string "? // Rreturn = // r/g. If the value of an element is of the string type, replace the carriage return character with "" ret. replace (rreturn, ""): // if the value is null, return ""; otherwise, return ret itself ret = null? "": Ret;} return; // if the value does not exist, directly return} // the following code mainly deals with the existence of parameters, that is, setting the value isFunction = jQuery. isFunction (value); // determines whether the parameter is Function type return this. each (function (I) {var val, self = jQuery (this); // if the node is not an element node, return if (this. nodeType! = 1) {return;} // if the parameter is of the Function type, val equals to the set value if (isFunction) {val = value returned by the Function parameter. call (this, I, self. val ();} else {// otherwise val is directly equal to the parameter value val = value;} // If val is equal to null/undefined, val = ""; if (val = null) {val = ""; // if val is numeric, convert the val value to the corresponding string type} else if (typeof val = "number") {val + = ""; // if val is an array type, convert to string} else if (jQuery. isArray (val) {val = jQuery. map (val, function (value) {Return value = null? "": Value + "" ;}) ;}// same as above, hooks is used to solve the browser compatibility problem (select, option, and other elements) hooks = jQuery. valHooks [this. type] | jQuery. valHooks [this. nodeName. toLowerCase ()]; // If set returns undefined, fall back to normal setting if (! Hooks |! ("Set" in hooks) | hooks. set (this, val, "value") === undefined) {this. value = val ;}});}

This method can obtain the current value of the first element in the matched element set, or set the value of each element in the matched element set.val()The method is used to obtain or set the value of a form element.

  • Val ()

Obtains the current value of the first element in the matched element set.

  • Val (value)

Set the value of each element in the matched element set.

    • Val (value)

      ValueA text string or an array in the form of a string to set the value of each matching element.

    • Val (function (index, value ))

      Function (index, value)A function used to return the set value.

The val () method of jQuery can not only set the value of an element, but also obtain the value of an element. Common Operations are operations on text boxes, such as determining email addresses. The val () method is also useful in enabling the select (drop-down list box), checkbox (multiple-choice box), and radio (single-choice) items to be selected, this is often used in form operations.

Certificate ----------------------------------------------------------------------------------------------------------------------------------------------------------

Today ends!

 

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.