繁体   English   中英

如何获得输入键来模拟按钮按下?

[英]How to get enter key to emulate a button press?

我正在开发一个天气应用程序,我只希望在按下 Enter 键或用户单击提交时执行代码。 问题是,只要按下任何键,代码就会执行,我不知道为什么? 这通常没什么大不了的,但它每次都请求 API 而我每分钟只收到 60 个请求,所以在那段时间里有两三个搜索会达到这个限制。

let button = document.querySelector("#button");
let searchBox = document.querySelector("#search-box");
let city = document.querySelector(".city");
let feelsLike = document.querySelector(".feels-like");
let temperature = document.querySelector(".temp");
let weatherDescription = document.querySelector(".weather");
let windSpeed = document.querySelector(".wind");
let icons = document.querySelector(".icons");
searchBox.addEventListener("keypress", function (event) {
  if (event.key === "Enter") {
    document.getElementById("button").click();
  }
  fetch(
    "https://api.openweathermap.org/data/2.5/weather?q=" +
      searchBox.value +
      "&units=metric&appid="
  )

...Rest of code to be executed

)};

我认为输入键模拟按钮按下是有意义的,但我不完全确定如何做到这一点 - 不幸的是,我在网上使用的任何资源都没有帮助。

在您的侦听searchBox.addEventListener("keypress", function (event) {..}中,您正在执行fetch function 每次按键发生时。因为if -condition 不会包含您的fetch执行。

尝试这个:

if (event.key === "Enter") {
    document.getElementById("button").click();
  
    fetch(
      "https://api.openweathermap.org/data/2.5/weather?q=" +
      searchBox.value +
      "&units=metric&appid="
    ) 
}

您应该将(获取)逻辑放在按钮的单击处理程序中。

其他几点:

  • 如果您在从fetch获得响应需要执行代码,则将该代码放入链式then回调中。 请注意, fetch返回的 promise 会解析为响应 object,并且您需要调用其中一个方法来获取另一个 promise,这反过来将解析为实际数据。
  • 不要调用.click() 最好将目标代码放在名为 function 中,然后在此处和按钮的单击处理程序中调用 function。
  • 您已经有了按钮的变量,因此无需再次调用getElemebtById
function process() {
  fetch(
    "https://api.openweathermap.org/data/2.5/weather?q=" +
      searchBox.value +
      "&units=metric&appid="
  ).then(function (response) {
     return response.json(); // <-- maybe? or .text() ?
  }).then(function (data) {
     //...Rest of code to be executed
  });
});

button.addEventListener("click", process);

searchBox.addEventListener("keypress", function (event) {
  if (event.key === "Enter") process();
)};

正如 Amacado 所说,获取在 if 之外。

此外,如果搜索框实际上是一个 HTML <input type="search">元素,那么已经有一个 OnSearch 事件处理程序,它考虑了回车键和手机键盘中的放大镜图标(搜索事件)。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM