[英]Form button keeps reloading page
This is in a form: <button class="addrecipe-button" type="submit" name="recipe-submit"></button>
这是一种形式:
<button class="addrecipe-button" type="submit" name="recipe-submit"></button>
Immediatley after I have this within a script tag:在我在脚本标签中有这个之后立即:
const addRecipeButton = document.querySelector(".addrecipe-button");
addRecipeButton.addEventListener("submit",addRecipe);
var recipeEntry = [];
const addRecipe = function(event){
event.preventDefault();
let recipe = {
type :document.querySelector(".recipe-type").value,
title :document.querySelector(".recipe-title").value,
description :document.querySelector(".recipe-description").value,
instructions :document.querySelector(".recipe-instructions").value,
photo :document.querySelector(".recipe-photo").value,
meats :document.querySelector(".recipe-meats").value,
dairy :document.querySelector(".recipe-dairy").value,
spices :document.querySelector(".recipe-spices").value,
fruitveg :document.querySelector(".recipe-fruitveg").value,
preptime :document.querySelector(".recipe-preptime").value,
cooktime :document.querySelector(".recipe-cooktime").value,
totaltime :document.querySelector(".recipe-totaltime").value
}
recipeEntry.push(recipe);
}
console.log(recipeEntry);
I can't understand why "event.preventDefault()" is not stopping the page from reloading.我不明白为什么“event.preventDefault()”没有阻止页面重新加载。 Also, the "recipeEntry" variable is staying empty when console.logged.
此外,“recipeEntry”变量在 console.logged 时保持为空。 Can someone please review my code?
有人可以查看我的代码吗?
Since the addRecipe
button is on a form you need to target the form rather than the button.由于
addRecipe
按钮位于表单上,因此您需要定位表单而不是按钮。 The button does not have a submit event.该按钮没有提交事件。 Change the selector to your form, maybe like this:
将选择器更改为您的表单,可能是这样的:
const addRecipeForm = document.querySelector("YOUR_FORM_SELECTOR");
addRecipeForm.addEventListener("submit",addRecipe);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.