From 218934fa2ed1c702a6d3923d2aa2cc6b43c48684 Mon Sep 17 00:00:00 2001 From: Peter Bengtsson Date: Tue, 8 Dec 2020 14:43:23 -0500 Subject: initial commit --- .../api/document_object_model/examples/index.html | 373 ++++++++++++++++++++ .../how_to_create_a_dom_tree/index.html | 145 ++++++++ .../zh-tw/web/api/document_object_model/index.html | 384 +++++++++++++++++++++ .../document_object_model/whitespace/index.html | 183 ++++++++++ .../\344\272\213\344\273\266/index.html" | 69 ++++ 5 files changed, 1154 insertions(+) create mode 100644 files/zh-tw/web/api/document_object_model/examples/index.html create mode 100644 files/zh-tw/web/api/document_object_model/how_to_create_a_dom_tree/index.html create mode 100644 files/zh-tw/web/api/document_object_model/index.html create mode 100644 files/zh-tw/web/api/document_object_model/whitespace/index.html create mode 100644 "files/zh-tw/web/api/document_object_model/\344\272\213\344\273\266/index.html" (limited to 'files/zh-tw/web/api/document_object_model') diff --git a/files/zh-tw/web/api/document_object_model/examples/index.html b/files/zh-tw/web/api/document_object_model/examples/index.html new file mode 100644 index 0000000000..66a1756da6 --- /dev/null +++ b/files/zh-tw/web/api/document_object_model/examples/index.html @@ -0,0 +1,373 @@ +--- +title: 使用 web 和 XML 開發來使用 DOM +slug: Web/API/Document_Object_Model/Examples +translation_of: Web/API/Document_Object_Model/Examples +--- +

本章介紹了使用 DOM 進行 Web 以及 XML 開發的一些長範例。只要可能,在例子就會使用通用的 JavaScript Web API 、技巧以及模式來操作文檔對象(the document object)。

+ +

範例一:高度和寬度

+ +

下面的例子展示了在不同尺寸的圖片時使用其高(height)和寬(width)屬性的情況:

+ +
<!DOCTYPE html>
+<html lang="en">
+<head>
+<title>width/height example</title>
+<script>
+function init() {
+  var arrImages = new Array(3);
+
+  arrImages[0] = document.getElementById("image1");
+  arrImages[1] = document.getElementById("image2");
+  arrImages[2] = document.getElementById("image3");
+
+  var objOutput = document.getElementById("output");
+  var strHtml = "<ul>";
+
+  for (var i = 0; i < arrImages.length; i++) {
+    strHtml += "<li>image" + (i+1) +
+            ": height=" + arrImages[i].height +
+            ", width=" + arrImages[i].width +
+            ", style.height=" + arrImages[i].style.height +
+            ", style.width=" + arrImages[i].style.width +
+            "<\/li>";
+  }
+
+  strHtml += "<\/ul>";
+
+  objOutput.innerHTML = strHtml;
+}
+</script>
+</head>
+<body onload="init();">
+
+<p>Image 1: no height, width, or style
+  <img id="image1" src="http://www.mozilla.org/images/mozilla-banner.gif">
+</p>
+
+<p>Image 2: height="50", width="500", but no style
+  <img id="image2"
+       src="http://www.mozilla.org/images/mozilla-banner.gif"
+       height="50" width="500">
+</p>
+
+<p>Image 3: no height, width, but style="height: 50px; width: 500px;"
+  <img id="image3"
+       src="http://www.mozilla.org/images/mozilla-banner.gif"
+       style="height: 50px; width: 500px;">
+</p>
+
+<div id="output"> </div>
+</body>
+</html>
+
+ +

範例二:圖片屬性

+ +
<!DOCTYPE html>
+<html lang="en">
+<head>
+<title>Modifying an image border</title>
+
+<script>
+function setBorderWidth(width) {
+  document.getElementById("img1").style.borderWidth = width + "px";
+}
+</script>
+</head>
+
+<body>
+<p>
+  <img id="img1"
+       src="image1.gif"
+       style="border: 5px solid green;"
+       width="100" height="100" alt="border test">
+</p>
+
+<form name="FormName">
+  <input type="button" value="Make border 20px-wide" onclick="setBorderWidth(20);" />
+  <input type="button" value="Make border 5px-wide"  onclick="setBorderWidth(5);" />
+</form>
+
+</body>
+</html>
+
+ +

範例三:改變樣式(style)

+ +

在下面這個簡單的例子中,透過取得的 DOM 元素中的 style 物件和 style 物件中的屬性,我們可以取得 HTML 段落中的一些基本樣式屬性。在本例中,你可以直接操控各別的樣式屬性。在下一個的例子裡(見例4),你可以使用 stylesheets 和它的規則來改變整個文檔的樣式。

+ +
<!DOCTYPE html>
+<html lang="en">
+<head>
+<title>Changing color and font-size example</title>
+
+<script>
+function changeText() {
+  var p = document.getElementById("pid");
+
+  p.style.color = "blue"
+  p.style.fontSize = "18pt"
+}
+</script>
+</head>
+<body>
+
+<p id="pid" onclick="window.location.href = 'http://www.cnn.com/';">linker</p>
+
+<form>
+  <p><input value="rec" type="button" onclick="changeText();" /></p>
+</form>
+
+</body>
+</html>
+
+ +

範例四:使用樣式表(stylesheets)

+ +

在文檔物件的 styleSheets 屬性會回傳一系列載入文檔中的樣式表(stylesheets)。你可以透過 styleSheets、style 和 CSSRule 物件來獲取樣式表和每條樣式規則。在下面的例子中,把所有的樣式規則中的選擇器文本(字符串)打印到控制台中。

+ +
var ss = document.styleSheets;
+
+for(var i = 0; i < ss.length; i++) {
+  for(var j = 0; j < ss[i].cssRules.length; j++) {
+    dump( ss[i].cssRules[j].selectorText + "\n" );
+  }
+}
+ +

下面是一個只定義了三條樣式規則的單一樣式表的文檔:

+ +
body { background-color: darkblue; }
+p { font-face: Arial; font-size: 10pt; margin-left: .125in; }
+#lumpy { display: none; }
+
+ +

該腳本會輸出如下的結果:

+ +
BODY
+P
+#LUMPY
+
+ +

範例五:事件傳遞

+ +

本例以一種簡單的方法闡述了事件是如何觸發以及在 DOM 中是如何處理的。當這個 HTML 文檔 BODY 載入的時候,在表格的首行註冊了一個事件監聽器。事件監聽器透過執行函數 stopEvent 來處理事件,從而改變在該表格底部的值。

+ +

然而,stopEvent 同時也會另外執行一個事件物件的方法{{domxref("event.stopPropagation")}},這會使得該事件(點擊)無法在 DOM 中有進一步的冒泡行為。請注意,表格本身有一個 {{domxref("element.onclick","onclick")}} 事件,使得這個表格被點擊時的時候原本應該要會跳出一個訊息。但因為 stopEvent 方法已經阻止了冒泡,所以在表格中的數據更新後,該事件階段有效地結束,表格的點擊事件沒有被觸發,而是顯示一個警告框(event propagation halted)——證實了事件被有效結束而沒有進一步冒泡。

+ +
<!DOCTYPE html>
+<html lang="en">
+<head>
+<title>Event Propagation</title>
+
+<style>
+#t-daddy { border: 1px solid red }
+#c1 { background-color: pink; }
+</style>
+
+<script>
+function stopEvent(ev) {
+  c2 = document.getElementById("c2");
+  c2.innerHTML = "hello";
+
+  // this ought to keep t-daddy from getting the click.
+  ev.stopPropagation();
+  alert("event propagation halted.");
+}
+
+function load() {
+  elem = document.getElementById("tbl1");
+  elem.addEventListener("click", stopEvent, false);
+}
+</script>
+</head>
+
+<body onload="load();">
+
+<table id="t-daddy" onclick="alert('hi');">
+  <tr id="tbl1">
+    <td id="c1">one</td>
+  </tr>
+  <tr>
+    <td id="c2">two</td>
+  </tr>
+</table>
+
+</body>
+</html>
+
+ +

Example 6: getComputedStyle

+ +

這個例子演示了如何用 {{domxref("window.getComputedStyle")}} 方法來獲取一個尚未被透過樣式元素或 JavaScript 設定的元素樣式(例如,elt.style.backgroundColor="RGB(173,216,230)")。列舉在 {{domxref("element.style", "elt.style")}} 後面的類型的樣式可以用更直接{{domxref("element.style", "elt.style")}} 屬性獲取。

+ +

getComputedStyle() 返回了一個 ComputedCSSStyleDeclaration 物件,其獨立的樣式屬性可以用該物件的 getPropertyValue() 方法引用,如同下面的例子一樣:

+ +
<!DOCTYPE html>
+<html lang="en">
+<head>
+
+<title>getComputedStyle example</title>
+
+<script>
+function cStyles() {
+  var RefDiv = document.getElementById("d1");
+  var txtHeight = document.getElementById("t1");
+  var h_style = document.defaultView.getComputedStyle(RefDiv, null).getPropertyValue("height");
+
+  txtHeight.value = h_style;
+
+  var txtWidth = document.getElementById("t2");
+  var w_style = document.defaultView.getComputedStyle(RefDiv, null).getPropertyValue("width");
+
+  txtWidth.value = w_style;
+
+  var txtBackgroundColor = document.getElementById("t3");
+  var b_style = document.defaultView.getComputedStyle(RefDiv, null).getPropertyValue("background-color");
+
+  txtBackgroundColor.value = b_style;
+}
+</script>
+
+<style>
+#d1 {
+  margin-left: 10px;
+  background-color: rgb(173, 216, 230);
+  height: 20px;
+  max-width: 20px;
+}
+</style>
+
+</head>
+
+<body>
+
+<div id="d1">&nbsp;</div>
+
+<form action="">
+  <p>
+    <button type="button" onclick="cStyles();">getComputedStyle</button>
+    height<input id="t1" type="text" value="1" />
+    max-width<input id="t2" type="text" value="2" />
+    bg-color<input id="t3" type="text" value="3" />
+  </p>
+</form>
+
+</body>
+</html>
+
+ +

範例七:顯示事件物件的屬性

+ +

這個例子使用 DOM 方法來顯示所有 {{domxref("window.onload")}} {{domxref("event")}} 物件的屬性及其在 table 中的值。這個方法也展示一個有用的技術,使用 for...in 迴圈來來遍歷一個物件的屬性,以得到它們的值。

+ +

不同瀏覽器之間事件物件的屬性有很大不同,WHATWG DOM Standard 規範了事件的標準屬性,然而,許多瀏覽器都大大擴展了這些。

+ +

將下面的代碼放到一個空白的文本文件,並將其用各種瀏覽器開啟,你一定會對各種瀏覽器之間的不一致(事件屬性的名稱及其數量)感到驚訝。你可能還喜歡在這個頁面加入一些元素,並呼叫不同的事件處理函數(event handlers)。

+ +
<!DOCTYPE html>
+<html lang="en">
+<head>
+<meta charset="utf-8"/>
+<title>Show Event properties</title>
+
+<style>
+table { border-collapse: collapse; }
+thead { font-weight: bold; }
+td { padding: 2px 10px 2px 10px; }
+
+.odd { background-color: #efdfef; }
+.even { background-color: #ffffff; }
+</style>
+
+<script>
+
+function showEventProperties(e) {
+  function addCell(row, text) {
+    var cell = row.insertCell(-1);
+    cell.appendChild(document.createTextNode(text));
+  }
+
+  var e = e || window.event;
+  document.getElementById('eventType').innerHTML = e.type;
+
+  var table = document.createElement('table');
+  var thead = table.createTHead();
+  var row = thead.insertRow(-1);
+  var lableList = ['#', 'Property', 'Value'];
+  var len = lableList.length;
+
+  for (var i=0; i<len; i++) {
+    addCell(row, lableList[i]);
+  }
+
+  var tbody = document.createElement('tbody');
+  table.appendChild(tbody);
+
+  for (var p in e) {
+    row = tbody.insertRow(-1);
+    row.className = (row.rowIndex % 2)? 'odd':'even';
+    addCell(row, row.rowIndex);
+    addCell(row, p);
+    addCell(row, e[p]);
+  }
+
+  document.body.appendChild(table);
+}
+
+window.onload = function(event){
+  showEventProperties(event);
+}
+</script>
+</head>
+
+<body>
+<h1>Properties of the DOM <span id="eventType"></span> Event Object</h1>
+</body>
+
+</html>
+
+ +

範例八:使用 DOM Table 介面

+ +

DOM HTMLTableElement 介面提供了一些方便的方法用於創建和操作資料表。兩種常用的方法是{{domxref("HTMLTableElement.insertRow")}}和{{domxref("tableRow.insertCell")}}.。

+ +

增加一行和一些細格到現有的資料表:

+ +
<table id="table0">
+ <tr>
+  <td>Row 0 Cell 0</td>
+  <td>Row 0 Cell 1</td>
+ </tr>
+</table>
+
+<script>
+var table = document.getElementById('table0');
+var row = table.insertRow(-1);
+var cell,
+    text;
+
+for (var i = 0; i < 2; i++) {
+  cell = row.insertCell(-1);
+  text = 'Row ' + row.rowIndex + ' Cell ' + i;
+  cell.appendChild(document.createTextNode(text));
+}
+</script>
+
+ +

提醒

+ + + + + + diff --git a/files/zh-tw/web/api/document_object_model/how_to_create_a_dom_tree/index.html b/files/zh-tw/web/api/document_object_model/how_to_create_a_dom_tree/index.html new file mode 100644 index 0000000000..02a3ac01e2 --- /dev/null +++ b/files/zh-tw/web/api/document_object_model/how_to_create_a_dom_tree/index.html @@ -0,0 +1,145 @@ +--- +title: 如何建立 DOM 樹 +slug: Web/API/Document_Object_Model/How_to_create_a_DOM_tree +translation_of: Web/API/Document_object_model/How_to_create_a_DOM_tree +--- +

{{draft}}

+ +

This page describes how to use the DOM Core API in JavaScript to create and modify DOM objects. It applies to all Gecko-based applications (such as Firefox) both in privileged (extensions) and unprivileged (web pages) code.

+ +

Dynamically creating a DOM tree

+ +

Consider the following XML document:

+ +
<?xml version="1.0"?>
+<people>
+  <person first-name="eric" middle-initial="H" last-name="jung">
+    <address street="321 south st" city="denver" state="co" country="usa"/>
+    <address street="123 main st" city="arlington" state="ma" country="usa"/>
+  </person>
+
+  <person first-name="jed" last-name="brown">
+    <address street="321 north st" city="atlanta" state="ga" country="usa"/>
+    <address street="123 west st" city="seattle" state="wa" country="usa"/>
+    <address street="321 south avenue" city="denver" state="co" country="usa"/>
+  </person>
+</people>
+
+ +

The W3C DOM API, supported by Mozilla, can be used to create an in-memory representation of this document like so:

+ +
var doc = document.implementation.createDocument("", "", null);
+var peopleElem = doc.createElement("people");
+
+var personElem1 = doc.createElement("person");
+personElem1.setAttribute("first-name", "eric");
+personElem1.setAttribute("middle-initial", "h");
+personElem1.setAttribute("last-name", "jung");
+
+var addressElem1 = doc.createElement("address");
+addressElem1.setAttribute("street", "321 south st");
+addressElem1.setAttribute("city", "denver");
+addressElem1.setAttribute("state", "co");
+addressElem1.setAttribute("country", "usa");
+personElem1.appendChild(addressElem1);
+
+var addressElem2 = doc.createElement("address");
+addressElem2.setAttribute("street", "123 main st");
+addressElem2.setAttribute("city", "arlington");
+addressElem2.setAttribute("state", "ma");
+addressElem2.setAttribute("country", "usa");
+personElem1.appendChild(addressElem2);
+
+var personElem2 = doc.createElement("person");
+personElem2.setAttribute("first-name", "jed");
+personElem2.setAttribute("last-name", "brown");
+
+var addressElem3 = doc.createElement("address");
+addressElem3.setAttribute("street", "321 north st");
+addressElem3.setAttribute("city", "atlanta");
+addressElem3.setAttribute("state", "ga");
+addressElem3.setAttribute("country", "usa");
+personElem2.appendChild(addressElem3);
+
+var addressElem4 = doc.createElement("address");
+addressElem4.setAttribute("street", "123 west st");
+addressElem4.setAttribute("city", "seattle");
+addressElem4.setAttribute("state", "wa");
+addressElem4.setAttribute("country", "usa");
+personElem2.appendChild(addressElem4);
+
+var addressElem5 = doc.createElement("address");
+addressElem5.setAttribute("street", "321 south avenue");
+addressElem5.setAttribute("city", "denver");
+addressElem5.setAttribute("state", "co");
+addressElem5.setAttribute("country", "usa");
+personElem2.appendChild(addressElem5);
+
+peopleElem.appendChild(personElem1);
+peopleElem.appendChild(personElem2);
+doc.appendChild(peopleElem);
+
+ +

See also the DOM chapter of the XUL Tutorial.

+ +

You can automate the creation of a DOM tree using a JXON reverse algorithm in association with the following JSON representation:

+ +
{
+  "people": {
+    "person": [{
+      "address": [{
+        "@street": "321 south st",
+        "@city": "denver",
+        "@state": "co",
+        "@country": "usa"
+      }, {
+        "@street": "123 main st",
+        "@city": "arlington",
+        "@state": "ma",
+        "@country": "usa"
+      }],
+      "@first-name": "eric",
+      "@middle-initial": "H",
+      "@last-name": "jung"
+    }, {
+      "address": [{
+        "@street": "321 north st",
+        "@city": "atlanta",
+        "@state": "ga",
+        "@country": "usa"
+      }, {
+        "@street": "123 west st",
+        "@city": "seattle",
+        "@state": "wa",
+        "@country": "usa"
+      }, {
+        "@street": "321 south avenue",
+        "@city": "denver",
+        "@state": "co",
+        "@country": "usa"
+      }],
+      "@first-name": "jed",
+      "@last-name": "brown"
+    }]
+  }
+}
+
+ +

So what?

+ +

DOM trees can be queried using XPath expressions, converted to strings or written to a local or remote files using XMLSerializer (without having to first convert to a string), POSTed to a web server (via XMLHttpRequest), transformed using XSLT, XLink, converted to a JavaScript object through a JXON algorithm, etc.

+ +

You can use DOM trees to model data which isn't well-suited for RDF (or perhaps you just don't like RDF). Another application is that, since XUL is XML, the UI of your application can be dynamically manipulated, downloaded, uploaded, saved, loaded, converted, or transformed quite easily.

+ +

See also

+ + + +

{{ languages( { "fr": "fr/Comment_cr\u00e9er_un_arbre_DOM", "ja": "ja/How_to_create_a_DOM_tree", "zh-cn": "zh-cn/How_to_create_a_DOM_tree" } ) }}

diff --git a/files/zh-tw/web/api/document_object_model/index.html b/files/zh-tw/web/api/document_object_model/index.html new file mode 100644 index 0000000000..a2e07c7fdd --- /dev/null +++ b/files/zh-tw/web/api/document_object_model/index.html @@ -0,0 +1,384 @@ +--- +title: 文件物件模型 (DOM) +slug: Web/API/Document_Object_Model +tags: + - DOM + - DOM Reference + - DOM 參考 + - Intermediate +translation_of: Web/API/Document_Object_Model +--- +

{{DefaultAPISidebar("DOM")}}

+ +

文件物件模型(Document Object Model, DOM是 HTML、XML 和 SVG 文件的程式介面。它提供了一個文件(樹)的結構化表示法,並定義讓程式可以存取並改變文件架構、風格和內容的方法。DOM 提供了文件以擁有屬性與函式的節點與物件組成的結構化表示。節點也可以附加事件處理程序,一旦觸發事件就會執行處理程序。 本質上,它將網頁與腳本或程式語言連結在一起。

+ +

雖然常常使用 JavaScript 來存取 DOM,但它本身並不是 JavaScript 語言的一部分,而且它也可以被其他語言存取(雖然不太常見就是了)。

+ +

這裡有一篇 DOM 的介紹可供查閱。

+ +

DOM 介面

+ +
+ +
+ +

棄用的 DOM 介面

+ +

文件物件模型正被大量的簡化。為了達成這個目的,下這些介面是在 DOM level 3 或更早的規範中就被刪掉了。由於不清楚是否會被再度納入,請姑且當他們已經被遺棄,並避免使用:

+ +
+ +
+ +

HTML 介面

+ +

一份包含 html 的文件會透過 {{domxref("HTMLDocument")}} 介面來描述。注意 HTML 規範也擴展了 {{domxref("Document")}} 介面。

+ +

HTMLDocument 物件也提供了瀏覽器功能的存取:分頁、透過 {{domxref("Window")}} 介面描繪頁面的視窗、與其相關的 {{domxref("window.style", "樣式")}} (通常是 CSS )、與本文關聯的瀏覽器 {{domxref("window.history", "歷史")}}、以及一個文件內的 {{domxref("Selection", "選擇器")}}。

+ +

HTML 元素介面

+ +
+ +
+ +

其他介面

+ +
+ +
+ +

棄用的 HTML 介面

+ +
+ +
+ +

SVG 介面

+ +

SVG 元素介面

+ +
+ +
+ +

SVG 資料型別介面

+ +

這裡是資料型態的 DOM API,在 SVG 特性和性質的定義中被使用。

+ +
+

備註:從 {{Gecko("5.0")}} 開始,下列 SVG 相關的 DOM 介面物件的表示清單,現在可以被索引且可以像陣列般被取用;此外,他們也有 length 屬性來標示其清單中的項目個數:{{domxref("SVGLengthList")}}、{{domxref("SVGNumberList")}}、{{domxref("SVGPathSegList")}},和 {{domxref("SVGPointList")}}。

+
+ +

靜態類型

+ +
+ +
+ +

動畫類型

+ +
+ +
+ +

SMIL 相關介面

+ +
+ +
+ +

其他的 SVG 介面

+ +
+ +
+ +

相關連結

+ + diff --git a/files/zh-tw/web/api/document_object_model/whitespace/index.html b/files/zh-tw/web/api/document_object_model/whitespace/index.html new file mode 100644 index 0000000000..7e584a3dd6 --- /dev/null +++ b/files/zh-tw/web/api/document_object_model/whitespace/index.html @@ -0,0 +1,183 @@ +--- +title: DOM 中的空白字元 +slug: Web/API/Document_Object_Model/Whitespace +tags: + - DOM + - 所有類別 +translation_of: Web/API/Document_Object_Model/Whitespace +--- +

問題說明

+

DOM 裡的空白字元會讓處理節點結構時增加不少麻煩。Mozilla 相關軟體中,原始文件裡所有空白字元都會在 DOM 中出現(不包括標籤內含的空白字元)。這樣的處理方式有其必要,一方面編輯器中可逕行排列文字、二方面 CSS 裡的 white-space: pre 也才能發揮作用。 如此一來就表示:

+ +

換句話說,下面這段程式碼的 DOM 節點結構就如附圖一般,其中「\n」代表換行字元:

+
<!-- My document -->
+<html>
+<head>
+  <title>My Document</title>
+</head>
+<body>
+  <h1>Header</h1>
+  <p>
+    Paragraph
+  </p>
+</body>
+</html>
+
+ +

+ +

這麼一來,要使用 DOM 遊走於節點結構間又不想要無用的空白字元時,會有點困難。

+

助你一臂之力

+

以下的 JavaScript 程式碼定義了許多函式,讓你處理 DOM 中的空白字元時能輕鬆點:

+
/**
+ * 以下所謂的「空白字元」代表:
+ *  "\t" TAB \u0009 (移位字元)
+ *  "\n" LF  \u000A (換行字元)
+ *  "\r" CR  \u000D (歸位字元)
+ *  " "  SPC \u0020 (真正的空白)
+ *
+ * 不包括 JavaScript 的「\s」,因為那代表如不斷行字元等其他字元。
+ */
+
+
+/**
+ * 測知某節點的文字內容是否全為空白。
+ *
+ * @參數   nod  |CharacterData| 類的節點(如  |Text|、|Comment| 或 |CDATASection|)。
+ * @傳回值      若 |nod| 的文字內容全為空白則傳回 true,否則傳回 false。
+ */
+function is_all_ws( nod )
+{
+  // Use ECMA-262 Edition 3 String and RegExp features
+  return !(/[^\t\n\r ]/.test(nod.data));
+}
+
+
+/**
+ * 測知是否該略過某節點。
+ *
+ * @參數   nod  DOM1 |Node| 物件
+ * @傳回值      若 |Text| 節點內僅有空白字元或為 |Comment| 節點時,傳回 true,
+ *              否則傳回 false。
+ */
+
+function is_ignorable( nod )
+{
+  return ( nod.nodeType == 8) || // 註解節點
+         ( (nod.nodeType == 3) && is_all_ws(nod) ); // 僅含空白字元的文字節點
+}
+
+/**
+ * 此為會跳過空白字元節點及註解節點的 |previousSibling| 函式
+ * ( |previousSibling| 是 DOM 節點的特性值,為該節點的前一個節點。)
+ *
+ * @參數   sib  節點。
+ * @傳回值      有兩種可能:
+ *               1) |sib| 的前一個「非空白、非註解」節點(由 |is_ignorable| 測知。)
+ *               2) 若該節點前無任何此類節點,則傳回 null。
+ */
+function node_before( sib )
+{
+  while ((sib = sib.previousSibling)) {
+    if (!is_ignorable(sib)) return sib;
+  }
+  return null;
+}
+
+/**
+ * 此為會跳過空白字元節點及註解節點的 |nextSibling| 函式
+ *
+ * @參數   sib  節點。
+ * @傳回值      有兩種可能:
+ *               1) |sib| 的下一個「非空白、非註解」節點。
+ *               2) 若該節點後無任何此類節點,則傳回 null。
+ */
+function node_after( sib )
+{
+  while ((sib = sib.nextSibling)) {
+    if (!is_ignorable(sib)) return sib;
+  }
+  return null;
+}
+
+/**
+ * 此為會跳過空白字元節點及註解節點的 |lastChild| 函式
+ * ( lastChild| 是 DOM 節點的特性值,為該節點之中最後一個子節點。)
+ *
+ * @參數   par  節點。
+ * @傳回值      有兩種可能:
+ *               1) |par| 中最後一個「非空白、非註解」節點。
+ *               2) 若該節點中無任何此類子節點,則傳回 null。
+ */
+function last_child( par )
+{
+  var res=par.lastChild;
+  while (res) {
+    if (!is_ignorable(res)) return res;
+    res = res.previousSibling;
+  }
+  return null;
+}
+
+/**
+ * 此為會跳過空白字元節點及註解節點的 |firstChild| 函式
+ *
+ * @參數   par  節點。
+ * @傳回值      有兩種可能:
+ *               1) |par| 中第一個「非空白、非註解」節點。
+ *               2) 若該節點中無任何此類子節點,則傳回 null。
+ */
+function first_child( par )
+{
+  var res=par.firstChild;
+  while (res) {
+    if (!is_ignorable(res)) return res;
+    res = res.nextSibling;
+  }
+  return null;
+}
+
+/**
+ * 此為傳回值不包含文字節點資料的首尾所有空白字元、
+ * 並將兩個以上的空白字元縮減為一個的 |data| 函式。
+ *( data 是 DOM 文字節點的特性值,為該文字節點中的資料。)
+ *
+ * @參數   txt 欲傳回其中資料的文字節點
+ * @傳回值     文字節點的內容,其中空白字元已依前述方式處理。
+ */
+function data_of( txt )
+{
+  var data = txt.data;
+  // Use ECMA-262 Edition 3 String and RegExp features
+  data = data.replace(/[\t\n\r ]+/g, " ");
+  if (data.charAt(0) == " ")
+    data = data.substring(1, data.length);
+  if (data.charAt(data.length - 1) == " ")
+    data = data.substring(0, data.length - 1);
+  return data;
+}
+
+

範例

+

以下示範上述函式的應用方法,在節點結構中依序檢查、找出內容為「"This is the third paragraph"」的節點,並修改其 class 屬性及文字內容。

+
var cur = first_child(document.getElementById("test"));
+while (cur)
+{
+  if (data_of(cur.firstChild) == "This is the third paragraph.")
+  {
+      cur.className = "magic";
+      cur.firstChild.data = "This is the magic paragraph.";
+  }
+  cur = node_after(cur);
+}
+
+
+

原文資訊

+ +
diff --git "a/files/zh-tw/web/api/document_object_model/\344\272\213\344\273\266/index.html" "b/files/zh-tw/web/api/document_object_model/\344\272\213\344\273\266/index.html" new file mode 100644 index 0000000000..ff4ecfe572 --- /dev/null +++ "b/files/zh-tw/web/api/document_object_model/\344\272\213\344\273\266/index.html" @@ -0,0 +1,69 @@ +--- +title: 事件與DOM +slug: Web/API/Document_Object_Model/事件 +translation_of: Web/API/Document_Object_Model/Events +--- +

Introduction

+ +

This chapter describes the DOM Event Model. The Event interface itself is described, as well as the interfaces for event registration on nodes in the DOM, and event listeners, and several longer examples that show how the various event interfaces relate to one another.

+ +

There is an excellent diagram that clearly explains the three phases of event flow through the DOM in the DOM Level 3 Events draft.

+ +

Also see Example 5: Event Propagation in the Examples chapter for a more detailed example of how events move through the DOM.

+ +

Registering event listeners

+ +

There are 3 ways to register event handlers for a DOM element.

+ +

EventTarget.addEventListener

+ +
// Assuming myButton is a button element
+myButton.addEventListener('click', function(){alert('Hello world');}, false);
+
+ +

This is the method you should use in modern web pages.

+ +

Note: Internet Explorer 6-8 didn't support this method, offering a similar {{domxref("EventTarget.attachEvent")}} API instead. For cross-browser compatibility use one of the many JavaScript libraries available.

+ +

More details can be found on the {{domxref("EventTarget.addEventListener")}} reference page.

+ +

HTML attribute

+ +
<button onclick="alert('Hello world!')">
+
+ +

The JavaScript code in the attribute is passed the Event object via the event parameter. The return value is treated in a special way, described in the HTML specification.

+ +

This way should be avoided. This makes the markup bigger and less readable. Concerns of content/structure and behavior are not well-separated, making a bug harder to find.

+ +

DOM element properties

+ +
// Assuming myButton is a button element
+myButton.onclick = function(event){alert('Hello world');};
+
+ +

The function can be defined to take an event parameter. The return value is treated in a special way, described in the HTML specification.

+ +

The problem with this method is that only one handler can be set per element and per event.

+ +

Accessing Event interfaces

+ +

Event handlers may be attached to various objects including DOM elements, document, the window object, etc. When an event occurs, an event object is created and passed sequentially to the event listeners.

+ +

The {{domxref("Event")}} interface is accessible from within the handler function, via the event object passed as the first argument. The following simple example shows how an event object is passed to the event handler function, and can be used from within one such function.

+ +
function foo(evt) {
+  // the evt parameter is automatically assigned the event object
+  alert(evt);
+}
+table_el.onclick = foo;
+
+ + + + -- cgit v1.2.3-54-g00ecf