【问题标题】:javascript input field returns "on" instead of value in consolejavascript输入字段返回“on”而不是控制台中的值
【发布时间】:2019-06-25 10:09:44
【问题描述】:

我在 JavaScript 中遇到问题。 我想在提交表单时从一系列单选按钮中获取值。
但是我总是得到on的值而不是应该是“A”、“B”或“C”的值,我不知道它为什么会这样。

这是js

const questionContainer = document.querySelector('#js-question-container');

const quizz = document.querySelector('.js-quizz');

const result = document.querySelector('.js-score');

const getQuestions = (callback) => {
    const request = new XMLHttpRequest();
    request.addEventListener('readystatechange', (() => {
        // console.log(request, request.readyState);
        if (request.readyState === 4 && request.status === 200) {
            const data = JSON.parse(request.responseText);
            callback(undefined, data);

        } else if (request.readyState === 4) {
            callback("Les données n'ont pas pu etre chargées", undefined);
        }

    }))
    request.open('GET', './questions.json');
    request.send();
}

getQuestions((err, data) => {
    console.log('callback fired !');
    console.log(err, data);

    let output = '';
    data.forEach(question => {
        output += `<p class="lead">${question.title}</p>`;
        question.answers.forEach(answer => {
            output += `<div class="form-check ${answer.value}">
            <input type="radio" class="form-radio answer${question.id}" name="q${question.id}" "value=${answer.value} ${shouldBeChecked(answer.id)}>
                <label class="form-check-label" for= "q${question.id}">${answer.sentence}</label>
        </div >`;
        });
        questionContainer.innerHTML = output;
        tryToDelegate();
        formSubmission(question);
    })
});

const formSubmission = (question) => {

    quizz.addEventListener('submit', e => {
        e.preventDefault();
        let score = 0;
        const userAnswers = [quizz.q0.value, quizz.q1.value, quizz.q2.value, quizz.q3.value];

        console.log('useranswers',userAnswers[3]);
        const correctAnswers = ["A", "B", "B", "B"];
        const nbQuestions = correctAnswers.length;
        let commentText = document.querySelector('.js-comment-text');

        userAnswers.forEach((answer, index) => {
            if (answer === correctAnswers[index]) {
                score += 1 / nbQuestions;
            }
            console.log('answer',answer, score);
            result.classList.remove('d-none');
            switch (score * 100) {
                case 0:
                    commentText.textContent = "Flatten by the ninja";
                    scrollToTop();
                    break;
                case 25:
                    commentText.textContent = "That's a pity score, please improve !";
                    scrollToTop();
                    break;
                case 50:
                    commentText.textContent = "On the way to the success !";
                    scrollToTop();
                    break;
                case 75:
                    commentText.textContent = "You nearly beat the ninja !";
                    scrollToTop();
                    break;
                case 100:
                    commentText.textContent = "The ninja is KO !";
                    scrollToTop();
                    break;
                default:
                    commentText.textContent = '';
            }

            let outputScore = 0;
            const timer = setInterval(() => {
                result.querySelector('.js-score-inner').innerHTML = `Your score is < span class="display-4 text-primary" > ${outputScore} %</span > `;
                if (outputScore === (score * 100)) {
                    clearInterval(timer)
                } else {
                    outputScore++;
                }

            }, 10);
        });
    })
}

let scrollToTop = () => {
    const topXOffset = document.querySelector('#top').offsetLeft;
    const topYOffset = document.querySelector('#top').offsetTop;

    window.scrollTo(topXOffset, topYOffset);
}
const tryToDelegate = () => {
    quizz.querySelectorAll('.form-check').forEach(item => {
        item.addEventListener('click', () => {
            item.querySelector('input[type="radio"]').setAttribute('checked', 'checked');
            var el = item.nextElementSibling;
            console.log(el);
        });
    })
}
const shouldBeChecked = element => {
    if (element === 0) {
        return 'checked';
    } else {return '';}
}

还有html文件

<!DOCTYPE html>
<!--[if lt IE 7]>      <html class="no-js lt-ie9 lt-ie8 lt-ie7"> <![endif]-->
<!--[if IE 7]>         <html class="no-js lt-ie9 lt-ie8"> <![endif]-->
<!--[if IE 8]>         <html class="no-js lt-ie9"> <![endif]-->
<!--[if gt IE 8]><!-->
<html class="no-js">
<!--<![endif]-->

<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <title>Quizz</title>
    <meta name="description" content="">
    <meta name="viewport" content="wvalueth=device-wvalueth, initial-scale=1">
    <!-- Compiled and minified CSS -->
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css"
        integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
    <link href="https://fonts.googleapis.com/css?family=Roboto&display=swap" rel="stylesheet">
    <link rel="stylesheet" href="./quizz.css">
</head>

<body>
    <div>
        <header class="intro py-3 bg-white text-center" id="top">
            <div class="container">
                <h2 class="text-primary display-3 my-4">Ninja quizz</h2>
            </div>
        </header>

        <div class="text-center py-4 js-score d-none bg-light">
            <div class="container lead">
                <span class="js-score-inner"></span>
                <p class=""><em class="js-comment-text"></em></p>
            </div>
        </div>
        <div class="questions py-4 bg-primary">
            <div class="container">
                <form class="js-quizz">
                    <div class="question text-white" id="js-question-container">
                    </div>
                    <div class="text-center"><input type="submit" value="Submit" class="btn btn-light"></div>
                </form>
            </div>
        </div>
    </div>
<script src="./quizz.js" async defer></script>
</body>

</html>

请注意,该项目会获取一个本地的 JSON 文件(这很好用),然后根据 JSON 文件提供的数据呈现一个表单。

【问题讨论】:

  • 发布您的代码或部分代码,而不是 github url
  • “我不知道为什么会这样。” - 因为on 是单选按钮使用的默认值,如果您没有明确指定不同的值。并且通过在 value 属性周围的部分中弄乱语法,您实际上没有指定一个。
  • @04FS。好的,我明白了,只是一个额外的双引号弄乱了我的代码。我应该买新眼镜:)

标签: javascript ecmascript-6


【解决方案1】:

在第 34 行对我来说,你有问题;

name="q${question.id}" "value=${answer.value} ${shouldBeChecked(answer.id)} - 价值问题

name="q${question.id}" value="${answer.value} ${shouldBeChecked(answer.id)"} 应该是

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-10-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多