在运行记录故障的函数之前,如何设置检查以查看搜索栏是否为空?
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);
}
这是实现这一目标的一种方法。我在运行之前添加了一个额外的条件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">
验证:
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句