簡體   English   中英

輸入類型:提交在 javascript 中不起作用?

[英]input type:submit not working in javascript?

我正在嘗試開發一個提出問題並具有 2 個選項的表單,最后是使用 javascript 提交類型的輸入。

HTML:

<div class="intro py-3 bg-white text-center">
  <div class="container">
    <h2 class="text-primary display-3 my-4">Ninja Quiz</h2>
  </div>
</div>

<div class=" quiz py-4 bg-primary">
  <div class="container">
    <h2 class="my-5 text-white">On with questions</h2>

    <form class="quiz-form text-light">
      <div class="my-5">
        <p class="lead font-weight-normal">
          1.How do you give Ninja Directions?
        </p>
        <div class="form-check my-2 text-white-50">
          <input type="radio" name="q1" id="q1" value="a" checked />
          <label for="q1" class="form-check-label">Show Them A map</label>
        </div>
        <div class="form-check my-2 text-white-50">
          <input type="radio" name="q1" id="q1" value="b" />
          <label for="q1" class="form-check-label"
            >Dont worry a ninja will find you</label
          >
        </div>
      </div>
      <div class="text-center">
        <input type="submit" class="btn btn-light" />
      </div>
    </form>
  </div>
</div>

我的 ts 頁面是:

import { Component, OnInit } from '@angular/core';
const correctAnswers = ['b'];
const form = document.querySelector('.quiz-form');

@Component({
  selector: 'app-udemy',
  templateUrl: './udemy.component.html',
  styleUrls: ['./udemy.component.css'],
})

export class UdemyComponent implements OnInit {
  constructor() {}

  ngOnInit(): void {}
  if(form) {
    form.addEventListener('submit', e => {
      console.log(form);
      e.preventDefault();
      let score = 0;
      const userAnswers = [form.q1.value];
      userAnswers.forEach((answer, index) => {
        if (answer === correctAnswers[index]) {
          score = 100;
        }
      });
      console.log(score);
    });
  }
}

我現在面臨的問題是當我點擊提交時沒有任何反應。 我的要求是,當我單擊提交時,會觸發eventListener並顯示分數。

這就是您在 angular 中使用表單的方式:

在組件中。html:

<form class="quiz-form text-light" 
    #myForm="ngForm" (ngSubmit)="submitForm(myForm)">

     <div class="form-check my-2 text-white-50">
      <input type="text" name="q1" id="q1" [(ngModel)]="q1" />
    </div>
        .....
      <div class="text-center">
         <input type="submit" class="btn btn-light" />
     </div>
</form>

component.ts中:

submitForm(form:any) {
    console.log(form.value);
  }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM