[英]Calling a function with an e.preventDefault without an e parameter
I have a function (which has an e
parameter) that's fired off in two ways:我有一个 function (它有一个
e
参数),它以两种方式触发:
Submitting a form;提交表格;
By changing between two elements.通过在两个元素之间进行更改。
I have a e.preventDefault()
at the end of the function because, otherwise, the page will reload and the asynchronous event onscreen would be disrupted.我在 function 的末尾有一个
e.preventDefault()
因为,否则,页面将重新加载并且屏幕上的异步事件将被中断。 This doesn't throw any errors when I call the function using the submit
event listener.当我使用
submit
事件侦听器调用 function 时,这不会引发任何错误。 However, when I try using the change
event listener, it shows an error of how e
isn't defined, and yet still works.但是,当我尝试使用
change
事件侦听器时,它显示e
未定义的错误,但仍然有效。 When I add an e
, the function refuses to work when called with the change
event.当我添加
e
时, function 在使用change
事件调用时拒绝工作。
Obviously, I could leave it alone because it still works, but I'd still like to know what to do.显然,我可以不理会它,因为它仍然有效,但我仍然想知道该怎么做。
Thank you in advance.先感谢您。
Edit for code:编辑代码:
Event Listeners事件监听器
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: Function:
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();
}
You need to pass the event
parameter from the event listener to getWeather
您需要将
event
参数从事件侦听器传递给getWeather
tempSelectForm.addEventListener("change", (e) => {
if (celsius.checked) {
measurement = true;
getWeather(e);
} else if (fahrenheit.checked) {
measurement = false;
getWeather(e);
}
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.