你好我在按Enter键时试图运行一个javascript函数.到目前为止,这是我的代码
我的HTML
<!DOCTYPE html>
<html>
<head>
<title>JS Bin</title>
</head>
<body>
<div>
<form id="inputForm">
<label for="userInput">Input : </label>
<span id="userInputSpan">
<input type="text" id="userInput" onkeydown="readInput(this)" />
</span>
</form>
</div>
</body>
</html>
Run Code Online (Sandbox Code Playgroud)
我的JAVASCRIPT
function readInput(e) {
if (e.keyCode == 13) { // 13 is enter key
// Execute code here.
// var temp = e.value;
// console.log(temp);
alert(e.value);
}
}
Run Code Online (Sandbox Code Playgroud)
这是我的JSBin
您将传递this给事件处理程序并将其用作event对象.
将元素实例和事件对象传递给事件处理程序.
<input type="text" id="userInput" onkeydown="readInput(this, event)" />
^^^^ ^^^^^
Run Code Online (Sandbox Code Playgroud)
并让他们在处理程序中
function readInput(el, e) {
^^ ^
// el: Element
// e: Event object
Run Code Online (Sandbox Code Playgroud)
window.onload = function() {
document.getElementById("userInput").focus();
};
function readInput(el, e) {
if (e.keyCode == 13) {
console.log(el.value);
}
}Run Code Online (Sandbox Code Playgroud)
<div>
<form id="inputForm">
<label for="userInput">Input :</label>
<span id="userInputSpan">
<input type="text" id="userInput" onkeydown="readInput(this, event)"/>
</span>
</form>
</div>Run Code Online (Sandbox Code Playgroud)
建议:
autofocus在输入时使用属性form提交,使用return false;或event.preventDefault()来自事件处理程序.document.addEventListener('DOMContentLoaded', function() {
document.getElementById('userInput').addEventListener('keydown', function(e) {
if (e.keyCode == 13) {
console.log(this.value);
e.preventDefault(); // Prevent default action i.e. submit form
// return false;
}
}, false);
});Run Code Online (Sandbox Code Playgroud)
<div>
<form id="inputForm">
<label for="userInput">Input :</label>
<span id="userInputSpan">
<input type="text" id="userInput" autofocus />
</span>
</form>
</div>Run Code Online (Sandbox Code Playgroud)