DIV CSS 佈局教程網

JS getAttribute 與 setAttribute 的使用介紹
編輯:關於JavaScript     

在JavaScript中,getAttribute 與 setAttribute 是用來讀取與設定元素屬性的兩個核心方法。本文透過一個簡單範例,示範如何取得與修改元素的title屬性。

・getAttribute:取得屬性。

・setAttribute:設定屬性。

完整程式碼如下:

<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Untitled Document</title>
<script language="JavaScript">
function change() {
  var input = document.getElementById("li1");
  alert(input.getAttribute("title"));
  input.setAttribute("title", "mgc");
  alert(input.getAttribute("title"));
}
</script>
</head>
<body>
<ul id="u">
<li id="li1" title="hello">Magci</li>
<li>J2EE</li>
<li>Haha!</li>
</ul>
<input type="button" value="Change" onClick="change();" />
</body>
</html>

運作說明

程式先以 getAttribute("title") 取得 li1 元素原本的title屬性並彈出顯示(結果為「hello」);接著用 setAttribute("title", "mgc") 將其修改為「mgc」;最後再次取得並顯示,即可看到屬性已被成功更新。透過這兩個方法,我們就能輕鬆地在執行階段動態讀寫元素的任意屬性。

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved