1. 程式人生 > >深入學習jquery原始碼之prop()與removeProp()

深入學習jquery原始碼之prop()與removeProp()

深入學習jquery原始碼之prop()與removeProp()

prop(name|properties|key,value|fn)

概述

獲取在匹配的元素集中的第一個元素的屬性值。

隨著一些內建屬性的DOM元素或window物件,如果試圖將刪除該屬性,瀏覽器可能會產生錯誤。jQuery第一次分配undefined值的屬性,而忽略了瀏覽器生成的任何錯誤

引數

name String

屬性名稱

properties Map

作為屬性的“名/值對”物件

key,value String,Object

屬性名稱,屬性值

key,function(index, attr) 

String,Function

1:屬性名稱。

2:返回屬性值的函式,第一個引數為當前元素的索引值,第二個引數為原先的屬性值。

選中複選框為true,沒選中為false

$("input[type='checkbox']").prop("checked");

禁用頁面上的所有複選框。

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

禁用和選中所有頁面上的複選框。

$("input[type='checkbox']").prop("disabled", false);
$("input[type='checkbox']").prop("checked", true);

通過函式來設定所有頁面上的複選框被選中。

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

 

removeProp(name)

概述

用來刪除由.prop()方法設定的屬性集

隨著一些內建屬性的DOM元素或window物件,如果試圖將刪除該屬性,瀏覽器可能會產生錯誤。jQuery第一次分配undefined值的屬性,而忽略了瀏覽器生成的任何錯誤

引數

propertyName String

要刪除的屬性名

設定一個段落數字屬性,然後將其刪除。

<p> </p>
var $para = $("p");
$para.prop("luggageCode", 1234);
$para.append("The secret luggage code is: ", String($para.prop("luggageCode")), ". ");
$para.removeProp("luggageCode");
$para.append("Now the secret luggage code is: ", String($para.prop("luggageCode")), ". ");
The secret luggage code is: 1234. Now the secret luggage code is: undefined. 

 

jquery原始碼

  var rfocusable = /^(?:input|select|textarea|button|object)$/i,
        rclickable = /^(?:a|area)$/i;

    jQuery.fn.extend({
        prop: function (name, value) {
            return access(this, jQuery.prop, name, value, arguments.length > 1);
        },

        removeProp: function (name) {
            name = jQuery.propFix[name] || name;
            return this.each(function () {
                // try/catch handles cases where IE balks (such as removing a property on window)
                try {
                    this[name] = undefined;
                    delete this[name];
                } catch (e) { }
            });
        }
    });

    jQuery.extend({
        propFix: {
            "for": "htmlFor",
            "class": "className"
        },

        prop: function (elem, name, value) {
            var ret, hooks, notxml,
                nType = elem.nodeType;

            // don't get/set properties on text, comment and attribute nodes
            if (!elem || nType === 3 || nType === 8 || nType === 2) {
                return;
            }

            notxml = nType !== 1 || !jQuery.isXMLDoc(elem);

            if (notxml) {
                // Fix name and attach hooks
                name = jQuery.propFix[name] || name;
                hooks = jQuery.propHooks[name];
            }

            if (value !== undefined) {
                return hooks && "set" in hooks && (ret = hooks.set(elem, value, name)) !== undefined ?
                    ret :
                    (elem[name] = value);

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

        propHooks: {
            tabIndex: {
                get: function (elem) {
                    // elem.tabIndex doesn't always return the correct value when it hasn't been explicitly set
                    // http://fluidproject.org/blog/2008/01/09/getting-setting-and-removing-tabindex-values-with-javascript/
                    // Use proper attribute retrieval(#12072)
                    var tabindex = jQuery.find.attr(elem, "tabindex");

                    return tabindex ?
                        parseInt(tabindex, 10) :
                        rfocusable.test(elem.nodeName) || rclickable.test(elem.nodeName) && elem.href ?
                        0 :
                        -1;
                }
            }
        }
    });

    // Some attributes require a special call on IE
    // http://msdn.microsoft.com/en-us/library/ms536429%28VS.85%29.aspx
    if (!support.hrefNormalized) {
        // href/src property should get the full normalized URL (#10299/#12915)
        jQuery.each(["href", "src"], function (i, name) {
            jQuery.propHooks[name] = {
                get: function (elem) {
                    return elem.getAttribute(name, 4);
                }
            };
        });
    }

    // Support: Safari, IE9+
    // mis-reports the default selected property of an option
    // Accessing the parent's selectedIndex property fixes it
    if (!support.optSelected) {
        jQuery.propHooks.selected = {
            get: function (elem) {
                var parent = elem.parentNode;

                if (parent) {
                    parent.selectedIndex;

                    // Make sure that it also works with optgroups, see #5701
                    if (parent.parentNode) {
                        parent.parentNode.selectedIndex;
                    }
                }
                return null;
            }
        };
    }

    jQuery.each([
        "tabIndex",
        "readOnly",
        "maxLength",
        "cellSpacing",
        "cellPadding",
        "rowSpan",
        "colSpan",
        "useMap",
        "frameBorder",
        "contentEditable"
    ], function () {
        jQuery.propFix[this.toLowerCase()] = this;
    });

    // IE6/7 call enctype encoding
    if (!support.enctype) {
        jQuery.propFix.enctype = "encoding";
    }