P粉8141609882023-08-22 09:33:55
//创建一个监听器,当你按下一个键时触发 window.onkeyup = keyup; //创建一个全局的Javascript变量 var inputTextValue; function keyup(e) { //将你的输入文本设置为全局的Javascript变量,每次按键都会更新 inputTextValue = e.target.value; //监听你按下回车键,此时你的网址将会改变为你在搜索框中输入的网址 if (e.keyCode == 13) { window.location = "http://www.myurl.com/search/" + inputTextValue; } }
P粉8284636732023-08-22 09:13:26
There are several ways to get the value of the input text box directly (without wrapping the input element inside a form element):
document.getElementById('textbox_id').value
Get the value of the required box
document.getElementById("searchTxt").value;
Note: Methods 2, 3, 4 and 6 return a collection of elements, so use [integer] to get the required elements. For the first element, use [0]
, for the second element, use [1]
, and so on...
Use document.getElementsByClassName('class_name')[integer].value
, which returns a real-time HTMLCollection
document.getElementsByClassName("searchField")[0].value;
, if this is the first text box on the page.
Use document.getElementsByTagName('tag_name')[integer].value
, which also returns a live HTMLCollection
document.getElementsByTagName("input")[0].value;
, if this is the first text box on the page.
document.getElementsByName('name')[integer].value
, it also returns a real-time NodeList
document.getElementsByName("searchTxt")[0].value;
, if this is the first text box named 'searchtext' on the page.
Use the powerful document.querySelector('selector').value
, which uses CSS selectors to select elements
document.querySelector('#searchTxt').value;
Select by iddocument.querySelector('.searchField').value;
Select by classdocument.querySelector('input').value;
Select by tag namedocument.querySelector('[name="searchTxt"]').value;
Select by namedocument.querySelectorAll('selector')[integer].value
, which also uses a CSS selector to select elements, but it returns all elements with that selector as a static NodeList.
document.querySelectorAll('#searchTxt')[0].value;
Select by iddocument.querySelectorAll('.searchField')[0].value;
Select by classdocument.querySelectorAll('input')[0].value;
Select by tag namedocument.querySelectorAll('[name="searchTxt"]')[0].value;
Select by namesupport
Browser | method 1 | Method 2 | Method 3 | Method 4 | Method 5/6 |
---|---|---|---|---|---|
IE6 | Y(problem) | N | Y | Y(problem) | N |
IE7 | Y(problem) | N | Y | Y(problem) | N |
IE8 | Y | N | Y | Y(problem) | Y |
IE9 | Y | Y | Y | Y(problem) | 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(problem) | Y |
Opera10.60 | |||||
Opera 12 | Y | Y | Y | Y | Y |