我有一个函数(具有e
参数),该函数有两种触发方式:
提交表格;
通过在两个元素之间切换。
我在函数末尾有一个e.preventDefault()
,因为否则,页面将重新加载,并且异步事件在屏幕上将被破坏。当我使用submit
事件监听器调用函数时,这不会引发任何错误。但是,当我尝试使用change
事件侦听器时,它显示了e
未被定义但仍然有效的错误。当我添加一个e
时,该函数在通过change
事件调用时拒绝工作。
显然,我可以不理会它,因为它仍然可以工作,但是我仍然想知道该怎么做。
谢谢你。
编辑代码:
事件监听器
searchForm.addEventListener("submit", getWeather);
// For the temperature preference
tempSelectForm.addEventListener("change", () => {
if (celsius.checked) {
measurement = true;
getWeather();
} else if (fahrenheit.checked) {
measurement = false;
getWeather();
}
});
功能:
function getWeather(e) {
// Data from the search
const text = search.value;
weather
.generateWeather(text, measurement)
.then((data) => {
if (data.cod === "404") {
console.log("No such city found");
} else if (data.cod === "400") {
console.log("No city detected");
} else {
console.log(data);
const placeName = data.name + ", " + data.sys.country;
const currentTemp = Math.floor(data.main.temp);
const weatherType = data.weather[0].main;
const weatherDescription = data.weather[0].description;
const feelsLike = Math.floor(data.main.feels_like);
const humidity = data.main.humidity;
const pressure = data.main.pressure;
const wind = data.wind.speed;
ui.showWeather(
measurement,
placeName,
currentTemp,
weatherType,
weatherDescription,
feelsLike,
humidity,
pressure,
wind
);
}
})
.catch((err) => console.error(err));
e.preventDefault();
}
您需要将event
参数从事件侦听器传递到getWeather
tempSelectForm.addEventListener("change", (e) => {
if (celsius.checked) {
measurement = true;
getWeather(e);
} else if (fahrenheit.checked) {
measurement = false;
getWeather(e);
}
});