zoukankan      html  css  js  c++  java
  • getAttribute与setAttribute用法

    getAttribute和setAttribute只能用于元素节点。

    1.当用getElementById获得元素节点时

    /*---------------------------index.html---------------------------*/

    <!DOCTYPE html>
    <html>
    <head><meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <meta name="Author" content="Hehe">
      <title>Shopping list</title>
    </head>
      <body>
       <p id="purchases" title="one">What to buy</p>
       <script type="text/javascript" src="script.js"></script>
      </body>
    </html>

    /*------------------------script.js---------------------------*/

    var paras=document.getElementById("purchases");
    alert(paras.getAttribute("title"));
    paras.setAttribute("title","abcd");
    alert(paras.getAttribute("title"));

    此时警告框一个显示one,一个显示abcd。

    2.当用getElementsByTagName获得元素节点时

    /*---------------------index.html-----------------------------*/

    <!DOCTYPE html>
    <html>
    <head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <meta name="Author" content="Hehe">
      <title>Shopping list</title>
    </head>
      <body>
       <p id="purchases" title="one">What to buy</p>
        <p title="two">What to buy</p>
       <script type="text/javascript" src="script.js"></script>
      </body>
    </html>

    /*----------------------------script.js--------------------*/

    var paras=document.getElementsByTagName("p");
    for(var i=0;i<paras.length;i++){
         paras[i].setAttribute("title","abcd");
         alert(paras[i].getAttribute("title"));
    }

    此时有俩个警告框显示abcd。

    :getElementById返回的是节点,getElementsByTagName返回的是数组。

          getAttribute("")与setAttribute("",A)都需要用到双引号A="字符"(即1.setAttribute("","a list of and so on")。2.A=”a list of and so on";setAttribute("",A)。)。

          alert()不是显示字符串不需要用到双引号。

  • 相关阅读:
    php的函数
    php字符串
    PDA触屏的终极解决办法
    数字万用表 选购指南
    WindowsXp Sp2 英文版
    访问局域网某台电脑时提示:无法访问,你可能没有权限使用网络资源.的解决办法
    中华人民共和国国家标准职工工伤与职业病致残程度鉴定
    删除所有设备驱动的批处理
    如何制作Win XP操作系统映像文件
    使用批处理和devcon.exe来控制 Windows 的设备
  • 原文地址:https://www.cnblogs.com/pcd12321/p/4193908.html
Copyright © 2011-2022 走看看