【问题标题】:how to check the searchBar field is empty and show an alert before running the getData function如何在运行 getData 函数之前检查 searchBar 字段是否为空并显示警报
【发布时间】:2021-08-19 22:56:18
【问题描述】:

如何在运行函数之前检查搜索栏是否为空,因为它正在记录故障?

const searchbar = document.querySelector('.search-bar');
searchbar.addEventListener('keypress', searchQuery);

function searchQuery(evt) {
  if (evt.keyCode == 13) {
    getData(searchbar.value);
  }
}

// Run a fetch requst on api to return the data from searchbox in metric units converting it into json
function getData(query) {
  fetch(`${api.base}weather?q=${query}&units=metric&APPID=${api.key}`)
    .then(weather => {
      return weather.json();
    }).then(displayData);
}

【问题讨论】:

  • searchbar.value && getData( searchbar.value )

标签: javascript input


【解决方案1】:

这是实现这一目标的一种方法。我在运行getData() 之前添加了一个额外的条件,它检查搜索框中的文本长度,并且仅在长度大于零时运行getData()(即搜索框中写了一些东西)。

const searchbar = document.querySelector('.search-bar');
searchbar.addEventListener('keypress', searchQuery);

function searchQuery(evt) {
  if (evt.keyCode == 13 && searchbar.value.length > 0) {
    getData(searchbar.value);
  }
}

function getData(query) {
  alert("Called the getData() function.")
}
<input type="text" class="search-bar">

验证:

  1. 在框中不输入任何内容并按 Enter:没有任何反应。
  2. 在框中输入内容并按回车键:将出现一条消息。

【讨论】:

    猜你喜欢
    • 2013-09-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-05-30
    • 2016-09-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多