【问题标题】:Form button keeps reloading page表单按钮不断重新加载页面
【发布时间】:2020-07-31 01:17:10
【问题描述】:

这是一种形式: <button class="addrecipe-button" type="submit" name="recipe-submit"></button>

在脚本标签中包含此内容后立即:

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);

我不明白为什么“event.preventDefault()”没有阻止页面重新加载。此外,“recipeEntry”变量在 console.logged 时保持为空。有人可以检查我的代码吗?

【问题讨论】:

    标签: javascript preventdefault


    【解决方案1】:

    由于addRecipe 按钮位于表单上,因此您需要定位表单而不是按钮。该按钮没有提交事件。将选择器更改为您的表单,可能是这样的:

    const addRecipeForm = document.querySelector("YOUR_FORM_SELECTOR");
                                    
    addRecipeForm.addEventListener("submit",addRecipe);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-03-11
      • 1970-01-01
      • 2013-10-13
      • 1970-01-01
      • 2022-11-11
      • 1970-01-01
      • 1970-01-01
      • 2023-03-13
      相关资源
      最近更新 更多