javascript代码实例教程-js便签笔记(4)――简单说说getAttributeNode()和setAttributeNode()

发布时间:2019-02-01 发布网站:脚本宝典
脚本宝典收集整理的这篇文章主要介绍了javascript代码实例教程-js便签笔记(4)――简单说说getAttributeNode()和setAttributeNode()脚本宝典觉得挺不错的,现在分享给大家,也给大家做个参考。
小宝典致力于为广大程序猿(媛)提供高品质的代码服务,请大家多多光顾小站,小宝典在此谢过。 1.前言:

前两天写过一片《分析dom元素的特性Attribute和属性Property》,分析了特性和属性的区别。那篇文章却忽略了一个主要知识点——getAttributeNode()和setattributeNode()

 

近来看《jQuery内幕》,今天正好看到jquery.attr()那一部分,忽然想起来这个方法。就此简单说一说。

 

 

 

2.从jQuery说起:

jQuery指出,在IE6、7下,浏览器的getAttribute()和setAttribute()不能正常获取和设置Attribute的值。jQuery做的测试类似于:

 

p1.classname = 'aaa';

alert(p1.getAttribute("className") === 'aaa');

IE6、7下或出现以上情况,即通过正常的 getAttribute("class")获取不到值。

 

那么在这种情况下,jQuery给出的解决方案是通过getAttributeNode("class").nodeValue获取,即可成功。相关代码如下:

 

复制代码

 1 if ( !getSetAttribute ) {

 2 

 3     //省略...

 4 

 5     // Use this for any attribute in IE6/7

 6     // This fixes almost every IE6/7 issue

 7     nodeHook = jQuery.valHooks.button = {

 8         get: function( elem, name ) {

 9             VAR ret;

10             ret = elem.getAttributeNode( name );

11             return ret && ( fixSPEcified[ name ] ? ret.nodeValue !== "" : ret.specified ) ?

12                 ret.nodeValue :

13                 undefined;

14         },

15         set: function( elem, value, name ) {

16             // Set the existing or create a new attribute node

17             var ret = elem.getAttributeNode( name );

18             if ( !ret ) {

19                 ret = document.createAttribute( name );

20                 elem.setAttributeNode( ret );

21             }

22             return ( ret.nodeValue = value + "" );

23         }

24     };

25 

26     //省略...

27 }

复制代码

 

 

3.如何应用:

3.1 getAttributeNode:

 

getAttributeNode()用法比较简单,它将返回一个Attr类型的对象,其nodeType === 2

 

<p id="p1" class="pClass"></p>

 

var className = p1.getAttributeNode("class").nodeValue;      //'pClass'

var tITle = p1.getAttributeNode("title");                    // null

var type = p1.getAttributeNode("class").nodeType;            // 2

 

 

3.2 setAttributeNode:

 

setAttributeNode()将接收一个Attr类型的对象,Attr类型的对象可用document直接创建:

 

<p id="p1" class="pClass"></p>

 

var attr = document.createAttribute(";myAttr");

attr.nodeValue = 'wang';

p1.setAttributeNode(attr);

运行以上代码,p1会加上一个“myAttr”的自定义特性:

 

 

 

 

 

4.最后:

加上对getAttributeNode()和setAttributeNode()的分析,对于htML特性和dom属性的分析就更全面了。

 

各位看官,如有发现问题,请尽管提出!在此谢过!

觉得可用,就经常来吧! 脚本宝典 欢迎评论哦! js脚本,巧夺天工,精雕玉琢。小宝典献丑了!

脚本宝典总结

以上是脚本宝典为你收集整理的javascript代码实例教程-js便签笔记(4)――简单说说getAttributeNode()和setAttributeNode()全部内容,希望文章能够帮你解决javascript代码实例教程-js便签笔记(4)――简单说说getAttributeNode()和setAttributeNode()所遇到的问题。

如果觉得脚本宝典网站内容还不错,欢迎将脚本宝典推荐好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。