gpt4 book ai didi

javascript - 当用户在输入字段中按 Enter 时如何运行函数?

转载 作者:行者123 更新时间:2023-12-02 16:41:42 25 4
gpt4 key购买 nike

我有一个输入字段,可以在提交时生成格式化文本。它与按钮配合使用效果很好,但我也希望它在用户按下 Enter 键时也能工作。

关于如何实现这一目标有什么想法吗?另外,当用户单击“添加”按钮时,我想将焦点返回到文本字段。

这是我的代码:

<!DOCTYPE html>
<html>
<head>
<title>Test</title>

<style>
.HiddenDiv{
color: red;
}
</style>

<script>
var counter = 0; //Prevents user from creating multiple nodes on submit
var limit = 5; //Amount of nodes that can be created per input field


//CREATES FORMATTED NODE FROM INPUT VALUE
function createNode(){
if (counter == limit) {
//Do nothing
}
else {
var input = document.getElementById('textInput1').value; //Retrieves input
var newText = document.createElement("li"); //Creates the HTML node
newText.innerHTML = input; //Sets the node's value to whatever is in the input

document.getElementById("Form").appendChild(newText); //Adds the node to the div

document.getElementById('textInput1').value=""; //Clears text field after submit
counter++;
}
}

//CLEARS THE FORM IF YOU MADE A MISTAKE
function deleteNode(){
var node = document.getElementById('Form');
while (node.hasChildNodes()) {
node.removeChild(node.firstChild);
counter=0;
}
}
</script>
</head>

<body>

<form method="POST">
<input type="text" id="textInput1">
<input type="button" value="Add" onClick="return createNode()">
<input type="button" value="Clear" onClick="return deleteNode()">
</form>

<div id="Form" class="HiddenDiv">
</div>

</body>
</html>

最佳答案

document.getElementById('textInput1').addEventListener('keypress', function (e) {
if (e.which === 13) {
e.stopPropagation();
e.preventDefault();

alert('Enter pressed');
}
});

演示:http://jsfiddle.net/p7twLf0v/

关于javascript - 当用户在输入字段中按 Enter 时如何运行函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27449273/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com