区分 DOM 属性和元素属性

区分 DOM 属性和元素属性

一个 img 标签:

<img src="images/image.1.jpg" id="hibiscus" alt="Hibiscus" class="classA" />

通常开发人员习惯将id,src,alt等叫做这个元素的"属性"。我们将其称为"元素属性"。但是在解析成 DOM 对象时,实际浏览器最后会将标签元素解析成"DOM 对象", 并且将元素的"元素属性"存储为"DOM 属性",两者是有区别的。

虽然我们设置了元素的 src 是相对路径:

images/image.1.jpg

但是在"DOM 属性"中都会转换成绝对路径:

http://localhost/images/image.1.jpg

甚至有些"元素属性"和"DOM 属性"的名称都不一样,比如上面的元素属性 class, 转换为 DOM 属性后对应 className。

牢记, 在 javascript 中我们可以直接获取或设置"DOM 属性":

<script type="text/javascript">
   $(function() {        var img1 = document.getElementById("hibiscus");
       alert(img1.alt);
       img1.alt = "Change the alt element attribute";
       alert(img1.alt);
   })</script>

所以如果要设置元素的 CSS 样式类, 要使用的是 DOM 属性"className"而不是元素属性"class:

img1.className = "classB";

在jQuery中没有包装操作"DOM属性"的函数, 因为使用javascript获取和设置"DOM属性"都很简单. 在jQuery提供了each()函数用于遍历jQuery包装集, 其中的this指针是一个DOM对象, 所以我们可以应用这一点配合原生javascript来操作元素的DOM属性:

   $("img").each(function(index) {    
      alert("index:" + index + ", id:" + this.id + ", alt:" + this.alt);    
     this.alt = "changed";    
        alert("index:" + index + ", id:" + this.id + ", alt:" + this.alt);    
     });

下面是each函数的说明: 

each( callback ) Returns: jQuery包装集 

对包装集中的每一个元素执行callback方法. 其中callback方法接受一个参数, 表示当前遍历的索引值,从0开始.


继续学习
||
<!DOCTYPE html> <html> <body> <p id="intro">Hello World!</p> <script> x=document.getElementById("intro"); document.write(x.firstChild.nodeValue); </script> </body> </html>
提交重置代码