如何使用Javascript向我的问卷中添加图片?

时间:2019-03-21 02:05:27

标签: javascript html css

在尝试向测验中添加图像时,我已经尝试了所有可以想到的方法。我对HTML编码还很陌生,但我很茫然。我正在尝试获取它,以便在打开网页时,在问题上方显示一个图像。

var myQuestions = [
    {
        question: "1. What are the warning signs of a phishing email?",
        answers: {
            A: 'Spelling errors',
            B:'Unfamiliar links',
            C: 'Asking for personal details',
            D: 'A, B and C'
        },
        correctAnswer: 'D'
    },
];

我不确定如何在测验中生成图像所需的代码。

var quizContainer = document.getElementById('quiz');
var resultsContainer = document.getElementById('results');
var submitButton = document.getElementById('submit');

generateQuiz(myQuestions, quizContainer, resultsContainer, submitButton);

function generateQuiz(questions, quizContainer, resultsContainer, submitButton) {

    function showQuestions(questions, quizContainer) {
        var output = [];
        var answers;
        for (var i = 0; i < questions.length; i++) {
            answers = [];
            for(letter in questions[i].answers) {
                answers.push(
                    '<label>'
                        + '<input type="radio" name="question'+i+'" value="'+letter+'">'
                        + letter + ': '
                        + questions[i].answers[letter]
                    + '</label>'
                );
            }
            output.push(
                '<div class="question">' + questions[i].question + '</div>'
                + '<div class="answers">' + answers.join('') + '</div>'
            );
        }
        quizContainer.innerHTML = output.join('');
    }
}

这是我必须显示的结果,以防万一。

function showResults(questions, quizContainer, resultsContainer) {
    var answerContainers = quizContainer.querySelectorAll('.answers');
    var userAnswer = '';
    var numCorrect = 0;

    for (var i = 0; i < questions.length; i++) {

        userAnswer = (answerContainers[i].querySelector('input[name=question'+i+']:checked')||{}).value;

        if(userAnswer===questions[i].correctAnswer) {
            numCorrect++;
            answerContainers[i].style.color = 'lightgreen';
        }
        else {
            answerContainers[i].style.color = 'red';
        }
    }
    resultsContainer.innerHTML = numCorrect + ' out of ' + questions.length;
}

showQuestions(questions, quizContainer);
submitButton.onclick = function() {
    showResults(questions, quizContainer, resultsContainer);
}

2 个答案:

答案 0 :(得分:1)

var img = document.createElement("img");

img.src = "image.png";
var src = document.getElementById("x");

src.appendChild(img);

答案 1 :(得分:1)

我告诉您,如果您想在每个问题上方添加图片,请在您使用的每个问题标签上方使用此代码。

<img src="source" border="n" align="top/bottom/left/right" width="n/n%" height="n/n%" >