2012年12月2日日曜日

TypeScript でタグ属性値の操作

helloworld2.html
  1. <!DOCTYPE html>  
  2. <html>  
  3.  <head>  
  4.   <meta charset="utf-8" />  
  5.   <title>hello world 2</title>  
  6.   <style type="text/css">  
  7.    #box { width: 150px; height: 150px; border: 1px solid #4c4c4c; }  
  8.    .red { background-color: #ffcccc; }  
  9.    .blue { background-color: #ccccff;}  
  10.   </style>  
  11.  </head>  
  12.  <body>  
  13.   <h1>Hello World 2</h1>  
  14.   
  15.   <div id="box">  
  16.    Hello World 2  
  17.   </div>  
  18.   
  19.   <img id="shape" src="circle.png"></img>  
  20.   
  21.     
  22.     
  23.   
  24.   <input type="button" value="get attributes" id="button1">  
  25.     
  26.   <script src="helloworld2.js"></script>  
  27.   
  28.  </body>  
  29. </html>  


helloworld2.ts
  1. function boxOver(e : MouseEvent) {  
  2.  box.className = "red";  
  3. }  
  4.   
  5. function boxNormal(e : MouseEvent) {  
  6.  box.className = "blue";  
  7. }  
  8.   
  9. function shapeOver(e : MouseEvent) {  
  10.  image.src = "star.png";  
  11. }  
  12.   
  13. function shapeNormal(e : MouseEvent) {  
  14.  image.src = "circle.png";  
  15. }  
  16.   
  17. function getAttributes(e : MouseEvent) {  
  18.  var attrs : Attr[] = box.attributes;  
  19.  var msg = "";  
  20.  for(var i = 0; i < attrs.length; i++) {  
  21.   var attr = attrs[i];  
  22.   msg = msg + attr.nodeName + ":" + attr.nodeValue + "\n";  
  23.  }  
  24.  alert(msg);  
  25. }  
  26.   
  27. var box : HTMLElement = document.getElementById("box");  
  28. box.addEventListener("mouseover", boxOver, false);  
  29. box.addEventListener("mouseout", boxNormal, false);  
  30.   
  31. var image : HTMLImageElement = <HTMLImageElement>document.getElementById("shape")  
  32. image.addEventListener("mouseover", shapeOver, false);  
  33. image.addEventListener("mouseout", shapeNormal, false);  
  34.   
  35. var btn1 : HTMLElement = document.getElementById("button1");  
  36. btn1.addEventListener("click", getAttributes, false);  


HTMLElement の attributes は Attr[] という配列になる。

0 件のコメント:

コメントを投稿