formObject.elements語法&再為short-circuit evaluation舉個例子
今天認識了這個語法,
Form elements Collection:
http://www.w3schools.com/jsref/coll_form_elements.asp
擷取重點如下:
--> returns a collection of all elements in a form.
--> The elements collection returns all elements inside the <form> element, not all <form> elements in the document.
接著來看例子,
想做的功能: 假設已填寫完所有文字欄位, 卻發現都填錯了, 希望能一鍵按下清空所有填錯的內容,
完整code如下:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
</head>
<body>
<form id="clearForm">
<input id="clearText" type="button" value="清空所有文字"><br>
<input type="text" value="文字1"><br>
<textarea>文字2</textarea>
</form>
<script>
window.onload = function() {
var _clearText = document.getElementById("clearText");
_clearText.onclick = function() {
var _elements = document.getElementById("clearForm").elements,
_elementsLen = _elements.length,
_ei = null,
i = 0;
for (; i < _elementsLen; i++) {
_ei = _elements[i];
(_ei.type == "text" || _ei.type == "textarea") && (_ei.value = ""); // short-circuit evaluation
}
};
};
</script>
</body>
</html>
Form elements Collection:
http://www.w3schools.com/jsref/coll_form_elements.asp
擷取重點如下:
--> returns a collection of all elements in a form.
--> The elements collection returns all elements inside the <form> element, not all <form> elements in the document.
接著來看例子,
想做的功能: 假設已填寫完所有文字欄位, 卻發現都填錯了, 希望能一鍵按下清空所有填錯的內容,
完整code如下:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
</head>
<body>
<form id="clearForm">
<input id="clearText" type="button" value="清空所有文字"><br>
<input type="text" value="文字1"><br>
<textarea>文字2</textarea>
</form>
<script>
window.onload = function() {
var _clearText = document.getElementById("clearText");
_clearText.onclick = function() {
var _elements = document.getElementById("clearForm").elements,
_elementsLen = _elements.length,
_ei = null,
i = 0;
for (; i < _elementsLen; i++) {
_ei = _elements[i];
(_ei.type == "text" || _ei.type == "textarea") && (_ei.value = ""); // short-circuit evaluation
}
};
};
</script>
</body>
</html>
留言
張貼留言