當頁面上有多個表單,而我們手上只有一個按鈕參照時,如何反過來找出這個按鈕所屬的表單?答案就在表單控制項的 form 屬性。任何表單元素(包含 button)都有一個 form 屬性,它會指向該元素所屬的表單物件,接著再取其 id 即可。
以下範例透過按鈕的 id 取得元素,再一路讀取所屬表單的 id:
<!DOCTYPE html>
<html>
<body>
<h1>www.sharejs.com</h1>
<form id="form1">
<button id="button1" type="button">Click me!</button>
</form>
<p>The id of the form containing the button is:
<script>
document.write(document.getElementById("button1").form.id);
</script></p>
</body>
</html>
執行結果如下:
The id of the form containing the button is: form1
這個技巧在事件委派、動態表單處理等情境中相當實用,因為它能讓你在只掌握子元素的情況下,快速回溯並操作母表單。