我正在使用 JavaScript 进行搜索。我会使用表格,但它会弄乱我页面上的其他内容。我有这个输入文本字段:
<input name="searchTxt" type="text" maxlength="512" id="searchTxt" class="searchField"/>
这是我的 JavaScript 代码:
<script type="text/javascript">
function searchURL(){
window.location = "http://www.myurl.com/search/" + (input text value);
}
</script>
如何将文本字段中的值导入 JavaScript?
最佳答案
有多种方法可以直接获取输入文本框的值(无需将输入元素包装在表单元素中):
方法一:
document.getElementById('textbox_id').value
to get the value of desired boxFor example,
document.getElementById("searchTxt").value;
Note: Method 2,3,4 and 6 returns a collection of elements, so use [whole_number] to get the desired occurrence. For the first element, use [0], for the second one use 1, and so on...
方法二:
Use
document.getElementsByClassName('class_name')[whole_number].value
which returns a Live HTMLCollectionFor example,
document.getElementsByClassName("searchField")[0].value;
if this is the first textbox in your page.
方法三:
Use
document.getElementsByTagName('tag_name')[whole_number].value
which also returns a live HTMLCollectionFor example,
document.getElementsByTagName("input")[0].value;
, if this is the first textbox in your page.
方法四:
document.getElementsByName('name')[whole_number].value
which also >returns a live NodeListFor example,
document.getElementsByName("searchTxt")[0].value;
if this is the first textbox with name 'searchtext' in your page.
方法五:
Use the powerful
document.querySelector('selector').value
which uses a CSS selector to select the elementFor example,
document.querySelector('#searchTxt').value;
selected by id
document.querySelector('.searchField').value;
selected by class
document.querySelector('input').value;
selected by tagname
document.querySelector('[name="searchTxt"]').value;
selected by name
方法六:
document.querySelectorAll('selector')[whole_number].value
which also uses a CSS selector to select elements, but it returns all elements with that selector as a static Nodelist.For example,
document.querySelectorAll('#searchTxt')[0].value;
selected by id
document.querySelectorAll('.searchField')[0].value;
selected by class
document.querySelectorAll('input')[0].value;
selected by tagname
document.querySelectorAll('[name="searchTxt"]')[0].value;
selected by name
支持
Browser Method1 Method2 Method3 Method4 Method5/6
IE6 Y(Buggy) N Y Y(Buggy) N
IE7 Y(Buggy) N Y Y(Buggy) N
IE8 Y N Y Y(Buggy) Y
IE9 Y Y Y Y(Buggy) Y
IE10 Y Y Y Y Y
FF3.0 Y Y Y Y N IE=Internet Explorer
FF3.5/FF3.6 Y Y Y Y Y FF=Mozilla Firefox
FF4b1 Y Y Y Y Y GC=Google Chrome
GC4/GC5 Y Y Y Y Y Y=YES,N=NO
Safari4/Safari5 Y Y Y Y Y
Opera10.10/
Opera10.53/ Y Y Y Y(Buggy) Y
Opera10.60
Opera 12 Y Y Y Y Y
有用的链接
关于javascript - 如何使用 JavaScript 获取文本输入字段的值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11563638/