javascript学习笔记(1)

这里介绍了javascript的4个基本方法的应用
    getElementById()
    getElementsByTagName()
    getAttribute()
    setAttribute()


这里还介绍了简单的css应用

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    
    <title>Welcome to try to use javascript</title>
    <meta http-equiv="Content-Type" content="text/html; charset=gb2312">
    <style>
    body {
      color:white;
      background-color:black;
    }
    .special{/*如果(body)css中其他地方没有class=special的话*/
      color:blue; 
      font-style:italic;    
    }
    /*h2的class=special*/
    h2.special{
      text-transform:uppercase;    
    }
    /*ul的独享样式*/
    #purchases{
      border:1px solid white;
      background-color:#333;
      color:#ccc;    
    }
    #purchases li{
      font-weight:bold;    
    }
    </style>
    <script type="text/javascript" src="example.js"></script> 	
    
  </head>
  
  <body>
    <h1>This is test javascript</h1>
    <h2 class="special">So do this</h2>
    <p class="special" title="this is a attribute">Don't forget to buy this stuff</p>
    <ul id="purchases">
       <li>A tin of beans</li>
       <li>Cheese</li>
       <li>Milk</li>     
    </ul>
    <script type="text/javascript">
       //测试getElementById()和getElementsByTagNam()
      //alert(typeof document.getElementById("purchases")); 
      var items=document.getElementsByTagName("li");
      for(var i=0;i<items.length;i++){
        alert(typeof items[i]); //输出object      
      } 
      var shopping=document.getElementById("purchases");
      var its=shopping.getElementsByTagName("*")
      //如果直接是document.getElementsByTagName("*")的话,找的是全部对象(object)
      alert(its.length);//输出 3, 3是ul中含有的3个li的数
      
      //测试getAttribute()
      var params=document.getElementsByTagName("p");
      for(var i=0;i<params.length;i++){
       // alert(params[i].getAttribute("title")); //输出object   
       //下面写法更容易理解
       var title_text=params[i].getAttribute("title");
       if(title_text!=null) alert(title_text);   
      } 
      
      //测试setAttribute()
      var shopping2=document.getElementById("purchases");
      alert("shopping2  "+shopping2.getAttribute("title"));//输出shopping2 null
      shopping2.setAttribute("title","a list of goods");
      alert("shopping2  "+shopping2.getAttribute("title"));//输出shopping a list of goods
    </script>
  </body>
</html>

你可能感兴趣的:(JavaScript,html,css)