首页 > 解决方案 > 我应该如何处理这个函数的时间

问题描述

在用户从我的 HTML 页面的输入元素中选择数据和年份后,我需要运行一些代码

这是我的 JavaScript 代码

var key_form = document.getElementById("key-form");
key_form.addEventListener("input", function () {
setTimeout(function(){let key = key_form.value; alert(key);}, 4000)
})

这是HTML

<!DOCTYPE html>
<html lang="en-US">
        <head>
            <title>Starter Template</title>
            <meta charset="UTF-8">
            <meta name="viewport" content="width=device-width, initial-scale=1.0">
            <meta http-equiv="X-UA-Compatible" content="ie=edge">
            <script src="src/script.js" defer></script>
            <link rel="stylesheet" href="src/styles.css"/>
        </head>
        <body>
            <label for="key-form">Pick date for key: </label>
            <input type="date" id="key-form"/>
            <label for="word">Word to encrypt: </label>
            <input type="text" id="word"/>
        </body>
</html>

有一个更好的方法吗?

编辑:

我不希望它有 4 秒的硬限制,然后运行它所做的代码。我希望它仅在用户完成输入后才运行该功能。

PS对不起,如果问题不清楚

标签: javascripthtml

解决方案


所以,问题是:你怎么知道“用户何时完成输入”

也许您的表单有一个用户必须单击的提交按钮?

const key_form = document.getElementById("key-form");
const submit_button = document.getElementById("submit-button");
submit_button.addEventListener("click", function () {
  let key = key_form.value;
  alert(key);
})
<label for="key-form">Pick date for key: </label>
<input type="date" id="key-form"/>
<label for="word">Word to encrypt: </label>
<input type="text" id="word"/>
<button id="submit-button">Encrypt word!</button>

或者当焦点不再在日期字段上时?

blur当您在字段外单击或在字段具有焦点时按 Tab 时触发该事件)

const key_form = document.getElementById("key-form");
key_form.addEventListener("blur", function () {
  let key = key_form.value;
  alert(key);
})
<label for="key-form">Pick date for key: </label>
<input type="date" id="key-form"/>
<label for="word">Word to encrypt: </label>
<input type="text" id="word"/>

还有其他方法。填写表单字段时会触发许多事件,它们都可以触发您想要的任何逻辑。所以想想你希望用户如何与这个表单交互,然后找到合适的事件来支持它。


推荐阅读