在本教程中,我们将学习如何使用 JavaScript 获取文本输入字段的值。
有几种方法可用于获取输入文本框值,而无需将输入元素包装在表单元素中。
让我们分别向我们展示它们并指出它们的不同之处。
第一种方法使用 document.getElementById('textboxId').value 来获取框的值:
document.getElementById("inputId").value;
<!DOCTYPE html> <html> <head> <title>文档的标题</title> </head> <body> <input type="text" placeholder="Type " id="inputId"> <button type="button" onclick="getInputValue();">Get Value</button> <script> function getInputValue() { //选择输入元素并获取其值 let inputVal = document.getElementById("inputId").value; //Displaying the value alert(inputVal); } </script> </body> </html>
我们还可以使用返回 Live HTMLCollection 的 document.getElementsByClassName('className')[wholeNumber].value 方法。
HTMLCollection 是一组 HTM/XML 元素:
document.getElementsByClassName("inpurClass")[0].value;
<!DOCTYPE html> <html> <head> <title>文档的标题</title> </head> <body> <input type="text" placeholder="Type " id="inputId" class="inputClass"> <button type="button" onclick="getInputValue();">Get Value</button> <script> function getInputValue() { //Selecting the input element and get its value let inputVal = document.getElementsByClassName("inputClass")[0].value; //Displaying the value alert(inputVal); } </script> </body> </html>
或者你可以使用 document.getElementsByTagName('tagName')[wholeNumber].value 它也返回一个 Live HTMLCollection:
document.getElementsByTagName("input")[0].value;
Live HTMLCollection 仅包含匹配的元素(例如类名或者标签名),不包含文本节点。
另一种方法是 document.getElementsByName('name')[wholeNumber].value,它返回一个活动的 NodeList,它是一个节点集合。
它包括任何 HTM/XML 元素,以及元素的文本内容:
document.getElementsByName("searchText")[0].value;
使用强大的 document.querySelector('selector').value 它使用 CSS 选择器来选择元素:
document.querySelector('#searchText').value; //selected by id document.querySelector('.search_Field').value; //selected by class document.querySelector('input').value; //selected by tagname document.querySelector('[name="searchText"]').value; //selected by name
还有另一种方法 document.querySelectorAll('selector')[wholeNumber].value 与前面的方法相同,但返回具有该选择器的所有元素作为静态节点列表:
document.querySelectorAll('#searchText')[0].value; //通过id选择 document.querySelectorAll('.search_Field')[0].value; //通过类名选择 document.querySelectorAll('input')[0].value; //通过标记名选择 document.querySelectorAll('[name="searchText"]')[0].value; //通过名称选择
节点列表Nodelist 和 HTML集合HTMLCollection
HTMLCollection 表示按文档顺序排列的元素的通用集合,建议从列表中选择的方法和属性。
HTML DOM 中的 HTMLCollection 是实时的,这意味着当文档发生更改时,它将自动更新。
NodeList 对象是由 Node.js 等属性返回的节点集合。
NodeList 有两种类型:活的和静态的。
当 DOM 中的任何更改不影响集合的内容时,它就是静态的。
并在 DOM 发生变化时自动更新集合。
我们可以使用 for 循环遍历 NodeList 中的项目。
不推荐使用 for...in 或者 for each...in。