博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
jQuery源码分析:jQuery对象属性设置(attr、access、$.attr)源代码分析
阅读量:4512 次
发布时间:2019-06-08

本文共 7487 字,大约阅读时间需要 24 分钟。

jQuery中设置对象属性有以下几种:

1、获取属性attr(name)  

$("img").attr("src");

2、设置属性attr(name,value)

$("img").attr("src","test.jpg");

3、批量设置属性attr(properties)

$("img").attr({ src: "test.jpg", alt: "Test Image" });

4、为所有匹配的元素设置一个计算的属性值,由这个函数计算的值作为属性值。 attr(key, function(index, attr))

$("img").attr("title", function() { return this.src });// 获取当前元素的src值作为title属性值

5、移除属性 removeAttr(name)

$("img").removeAttr("src");

其中都会用到jQuery对象的attr方法,attr的源代码如下:

jQuery.fn.extend({     attr: function( name, value ) {         return access( this, name, value, true, jQuery.attr );     })

可以看到,attr只是起到一个传值的作用,然后返回的是access的返回值,再来看看access函数中的代码:

function access( elems, key, value, exec, fn, pass) {     var length = elems.length;     // 如果key是对象,则拆分成名值单独赋值     if ( typeof key === "object" ) {         for ( var k in key ) {             access( elems, k, key[k], exec, fn, value );         }         return elems;     }          // 如果value含值,则给属性赋值     if ( value !== undefined ) {          // 如果value为函数的时候综合判断是否需要执行此函数         // 判断VALUE是否为函数,是函数则exec为true         exec = !pass && exec && jQuery.isFunction(value);          // 拆分对象,单独赋值         for ( var i = 0; i < length; i++ ) {             // 对单独的对象调用jQuery.attr,设置属性             // 如果value是函数则执行value.call( elems[i], i, fn( elems[i], key ) )             fn( elems[i], key, exec ? value.call( elems[i], i, fn( elems[i], key ) ) : value, pass);         }         // 返回对象数组         return elems;     }          // 如果上面的条件都不符合,length有值则获取属性值,无对象则为undefined     return length ? fn( elems[0], key ) : undefined; }

access就像它单词的意思一样是一个入口,判断key、value值的不同类型,最终会把值传递给jQuery的静态方法attr处理,即($.attr()):

attr静态方法中分别对浏览器的兼容性、各种特殊属性做了相应的处理

jQuery.extend({    attrFn: {        val: true,        css: true,        html: true,        text: true,        data: true,        width: true,        height: true,        offset: true    },            attr: function( elem, name, value, pass ) {        // don't set attributes on text and comment nodes        // 如果对象为空、文字、注释则返回undefined        if ( !elem || elem.nodeType === 3 || elem.nodeType === 8 ) {            return undefined;        }        // 如果 name为 val、css、html、text、data、width、height、offset        // 则直接调用jquery对应的方法如:$('p').html(value);        if ( pass && name in jQuery.attrFn ) {            return jQuery(elem)[name](value);        }        // 不是xml文档        var notxml = elem.nodeType !== 1 || !jQuery.isXMLDoc( elem ),            // Whether we are setting (or getting)            // 是否需要设置或者获取            set = value !== undefined;        // Try to normalize/fix the name        // 转换为适配的属性,如 class -> className        name = notxml && jQuery.props[ name ] || name;        // Only do all the following if this is a node (faster for style)        // 元素element 对象        if ( elem.nodeType === 1 ) {            // These attributes require special treatment            // rspecialurl = /href|src|style/            var special = rspecialurl.test( name );            // Safari mis-reports the default selected property of an option            // Accessing the parent's selectedIndex property fixes it            /*            *  以下为opselected的bug修复            *  http://www.cnblogs.com/GrayZhang/archive/2010/10/28/feature-detection-jquery1-4.html            * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~                                       ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~             以下为各浏览器中运行结果:             浏览器      | 结果             ----------- | -----             IE6         | false             IE7         | false             IE8         | false             IE9 beta    | false             Firefox 3.6 | true             Chrome 7    | true             Safari 5    | false             经测试,IE系列和Safari使用`appendChild`对空的``元素的`selectedIndex`属性,强迫浏览器计算`

转载于:https://www.cnblogs.com/NNUF/archive/2012/11/02/2746261.html

你可能感兴趣的文章
Python——thread
查看>>
Python网络编程(4)——异步编程select & epoll
查看>>
中国智能车未来挑战赛——复杂交通环境认知基础能力离线测试
查看>>
app之间的跳转
查看>>
javascript event loop
查看>>
LIS
查看>>
FastIO
查看>>
字符串循环右移-c语言
查看>>
解决从pl/sql查看oracle的number(19)类型数据为科学计数法的有关问题
查看>>
古训《增广贤文》
查看>>
职场的真相——七句话
查看>>
xcode命令行编译时:codesign命令,抛出“User interaction is not allowed.”异常 的处理...
查看>>
[转载]开机出现A disk read error occurred错误
查看>>
STM32 C++编程 002 GPIO类
查看>>
无线冲方案 MCU vs SoC
查看>>
进程装载过程分析(execve系统调用分析)
查看>>
在windows 7中禁用media sense
查看>>
ELK-Elasticsearch安装
查看>>
anglar JS使用两层ng-repeat嵌套使用,分辨$index
查看>>
Android 模拟器(Emulator)访问模拟器所在主机
查看>>