为什么创建的功能无法正常工作?

时间:2020-02-12 13:48:09

标签: javascript dom-events

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

html

{
"cucumberautocomplete.steps": [
    "src/test/features/step_definitions/*.ts"
],
"cucumberautocomplete.syncfeatures": "src/test/features/*feature",
"cucumberautocomplete.strictGherkinCompletion": true,
"files.exclude": {
    // include the defaults from VS Code
    "**/.git": true,
    "**/.DS_Store": true,

    // exclude .js and .js.map files, when in a TypeScript project
    "**/*.js": { "when": "$(basename).ts"},
    "**/*.js.map": true
}

,此处的Javascript代码是:

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

2 个答案:

答案 0 :(得分:2)

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

document.getElementById("libraryform")

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

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

答案 1 :(得分:0)

有两点需要更改

1。 来自

let librarysubmit = document.getElementById("librarysubmit");

let librarysubmit = document.getElementById('libraryform');

因为-表单上触发了提交事件。

  1. e.preventdefault()更改为e.preventDefault();,默认情况下将D大写。

演示链接:https://codepen.io/punith/pen/GRJpOrz?editors=1011