zoukankan      html  css  js  c++  java
  • jQuery removeAttr() 源码解读

    removeAttr比attr的代码要简单很多~~~

        removeAttr: function( name ) {
            return this.each(function() {
                jQuery.removeAttr( this, name );
            });
        },

    内部调用了jQuery.removeAttr方法,所以我们直接看它就可以啦~~

        removeAttr: function( elem, value ) {
            var name, propName,
                i = 0,
                //core_rnotwhite=/S+/g
                //value存在并且value可以匹配非空白字符
                //这一步很帅的一点就是它不动声色地把多空格分隔的字符串转为数组,所以removeAttr是可以同时移除多个属性的
                attrNames = value && value.match( core_rnotwhite );
    
            if ( attrNames && elem.nodeType === 1 ) {//属性节点
                while ( (name = attrNames[i++]) ) {
                    //propFix 属性修正
                    propName = jQuery.propFix[ name ] || name;
    
                    // Boolean attributes get special treatment (#10870)
                    //jQuery.expr.match.bool=/^(?:checked|selected|async|autofocus|autoplay|controls|defer|disabled|hidden|ismap|loop|multiple|open|readonly|required|scoped)$/i 
                    if ( jQuery.expr.match.bool.test( name ) ) {
                        // Set corresponding property to false
                        elem[ propName ] = false;
                    }
    
                    elem.removeAttribute( name );
                }
            }
        }
    console一下jQuery.propFix,我们发现,它原来是这样一个对象:

    cellpadding-->cellPadding ...

    是对大小写的修正,都转为小驼峰法

    class-->className  for-->htmlFor

    是考虑到js中关键字,所以将class映射到className ,js原生中就可以用element.getAttribute("className")

    再看jQuery.expr.match.bool这个正则,它匹配的这些属性如checked、selected、async都是bool属性,jquery为什么要特别加一句
    elem[ propName ] = false;呢?

    因为对于低版本的IE(6、7)来说,单单removeAttribute并不能移除bool属性。不加这一句,我们$().attr("checked")的时候,还是会返回“checked”。

    测试如下:
    DEMO1
    <body>
    <input id="ck" type="checkbox" checked>
    <script type="text/javascript">
    var ck=document.getElementById('ck');
    //ck.checked=false;
    ck.removeAttribute('checked');
     alert(ck.getAttribute("checked"));
    </scrip

    DEMO2

    <body>
    <input id="ck" type="checkbox" checked>
    <script type="text/javascript">
    var ck=document.getElementById('ck');
    ck.checked=false;
    ck.removeAttribute('checked');
     alert(ck.getAttribute("checked"));
    </script>
    </body>



  • 相关阅读:
    UIImageView的动画效果(左右移动、旋转、缩放)
    图片点击放大,再次点击回到原来状态(图片缩放)
    设置一个视图控制器为底部视图的方法
    Pods written in Swift can only be integrated as frameworks; add `use_frameworks!` to your Podfile or target to opt into using it. The Swift Pods being used are: ReactiveCocoa, ReactiveSwift, and Resul
    cocoaPod的使用
    cocoaPod安装过程
    RAC(reactivecocoa)的使用方法
    百度地图定位
    <NET CLR via c# 第4版>笔记 第11章 事件
    <NET CLR via c# 第4版>笔记 第10章 属性
  • 原文地址:https://www.cnblogs.com/qianlegeqian/p/4123893.html
Copyright © 2011-2022 走看看