Javascript/Typescript - 防止表单在提交时重置

Mar*_*oLe 1 javascript forms form-submit onsubmit typescript

我有一个简单的打字稿类,想要在提交时显示输入结果.尽管这个问题已经被问到,但是event.preventDefault()没有用.也许你可以给我一些提示?

class LoginPanel {

    public appDiv: HTMLElement = document.getElementById('app');

    constructor() {
        this.setForm();
        let btn = document.getElementById('loginButton');
        btn.addEventListener('submit', (event) => {event.preventDefault(); this.submitForm()});
    }

    public setForm(): void {
        this.appDiv.innerHTML = `<form id="loginForm" class="form-signin mt-5">
      <div class="text-center">
      <h1 class="h3 mb-3 font-weight-normal">Please sign in</h1>
      </div>
      <label for="inputEmail" class="sr-only">Email address</label>
      <input type="email" id="inputEmail" class="form-control" placeholder="Email address" required="" autofocus="">
      <label for="inputPassword" class="sr-only">Password</label>
      <input type="password" id="inputPassword" class="form-control mt-1" placeholder="Password" required="">
      <button id="loginButton" class="btn btn-lg btn-primary btn-block" type="submit">Sign in</button>
    </form>
    `;
    }

    public submitForm(): void {
        const elementFirst: HTMLElement = document.createElement('pre');
        const elementSecond: HTMLElement = document.createElement('pre');

        elementFirst.innerHTML = 'email: ' + document.getElementById('loginForm')[0].value;
        document.getElementById('loginForm').appendChild(elementFirst);

        elementSecond.innerHTML = 'password: ' + document.getElementById('loginForm')[1].value;
        document.getElementById('loginForm').appendChild(elementSecond);
    }

}

new LoginPanel();
Run Code Online (Sandbox Code Playgroud)

And*_*chi 5

提交表单时,您需要提交其所有值,而不仅仅是一个按钮.

因此,防止默认的正确位置在表单元素本身内,而不是其按钮.

constructor() {
    this.setForm();
    const form = document.getElementById('loginForm');
    form.addEventListener('submit', (event) => {event.preventDefault(); this.submitForm()});
}
Run Code Online (Sandbox Code Playgroud)

你可以看到它可以在这个CodePen中工作.