我当时在图书馆项目上工作,当有人按下添加按钮Javascript并不得不在控制台中打印“嘿,很好,您已经提交了表格”,它没有用。请帮忙。

html

<form id="libraryform">
  <div class="form-group row">
    <label for="bookname" class="col-sm-2 col-form-label">name</label>
    <div class="col-sm-10">
      <input type="text" class="form-control" id="bookname" placeholder="book name pls">
    </div>
  </div>
  <div class="form-group row">
    <label for="author" class="col-sm-2 col-form-label">author</label>
    <div class="col-sm-10">
      <input type="text" class="form-control" id="author" placeholder="author pls ">
    </div>
  </div>
  <fieldset class="form-group">
    <div class="row">
      <legend class="col-form-label col-sm-2 pt-0">genre of book</legend>
      <div class="col-sm-10">
        <div class="form-check">
          <input class="form-check-input" type="radio" name="type" id="fiction" value="fiction" checked>
          <label class="form-check-label" for="fiction">fiction</label>
        </div>
        <div class="form-check">
          <input class="form-check-input" type="radio" name="type" id="programming" value="programming">
          <label class="form-check-label " for="programming">computer programming</label>
        </div>
        <div class="form-check ">
          <input class="form-check-input" type="radio" name="type" id="cooking" value="cooking">
          <label class="form-check-label" for="cooking">cooking</label>
        </div>
      </div>
    </div>
  </fieldset>
  <div class="form-group row">
    <div class="col-sm-10">
      <button type="submit" id="librarysubmit" class="btn btn-primary">add book</button>
    </div>
  </div>
</form>


这里的Javascript代码是:

let librarysubmit = document.getElementById("librarysubmit");
librarysubmit.addEventListener('submit', libraryformsubmit);
function libraryformsubmit() {
    console.log("hey great u have submitted the form ");
    e.preventdefault()
    e.preventdefault()
}

最佳答案

您正在使用按钮上的事件提交。您需要在表格上附加事件。

喜欢

document.getElementById("libraryform")


而且您的js函数无效,您忘记了params事件

function libraryformsubmit(e) {
  console.log("hey great u have submitted the form ");
  e.preventDefault()
}

关于javascript - 为什么创建的功能不起作用?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/60189834/

10-12 12:36
查看更多