Я создаю тест на Javascript, но вместо этого хочу заменить свои вопросы изображениями. то есть логотипы языков программирования. Я видел другие примеры, но ни одного из того, что мне нужно. Если бы кто-нибудь мог помочь, я был бы очень признателен. Извините, что фрагмент не работает, не используйте его. Я надеюсь, что приведенный ниже код поможет объяснить то, что я прошу
function populate() {
if (quiz.isEnded()) {
showScores();
} else {
// show question
var element = document.getElementById("question");
element.innerHTML = quiz.getQuestionIndex().text;
// show options
var choices = quiz.getQuestionIndex().choices;
for (var i = 0; i < choices.length; i++) {
var element = document.getElementById("choice" + i);
element.innerHTML = choices[i];
guess("btn" + i, choices[i]);
}
showProgress();
}
};
function guess(id, guess) {
var button = document.getElementById(id);
button.onclick = function() {
quiz.guess(guess);
//populate();
}
};
function showProgress() {
var currentQuestionNumber = quiz.questionIndex + 1;
var element = document.getElementById("progress");
element.innerHTML = "Question " + currentQuestionNumber + " of " + quiz.questions.length;
};
function showScores() {
var gameOverHTML = "<h1>Result</h1>";
gameOverHTML += "<h2 id='score'> Your scores: " + quiz.score + "</h2>";
var element = document.getElementById("quiz");
element.innerHTML = gameOverHTML;
};
// create questions
var questions = [
new Question("Which one is not an object oriented programming language?", ["Java", "C#", "C++", "C"], "C"),
new Question("Which language is used for styling web pages?", ["HTML", "JQuery", "CSS", "XML"], "CSS"),
new Question("There are ____ main components of object oriented programming.", ["1", "6", "2", "4"], "4"),
new Question("Which language is used for web apps?", ["PHP", "Python", "Javascript", "All"], "All"),
new Question("MVC is a ____.", ["Language", "Library", "Framework", "All"], "Framework")
];
function Question(text, choices, answer) {
this.text = text;
this.choices = choices;
this.answer = answer;
}
Question.prototype.isCorrectAnswer = function(choice) {
return this.answer === choice;
}
function Quiz(questions) {
this.score = 0;
this.questions = questions;
this.questionIndex = 0;
}
Quiz.prototype.getQuestionIndex = function() {
return this.questions[this.questionIndex];
}
Quiz.prototype.guess = function(answer) {
if (this.getQuestionIndex().isCorrectAnswer(answer)) {
this.score++;
}
this.questionIndex++;
}
Quiz.prototype.isEnded = function() {
return this.questionIndex === this.questions.length;
}
// create quiz
var quiz = new Quiz(questions);
// display quiz
populate();body {
background-color: #eeeeee;
}
.grid {
width: 600px;
height: 500px;
margin: 0 auto;
background-color: #fff;
padding: 10px 50px 50px 50px;
border-radius: 50px;
border: 2px solid #cbcbcb;
box-shadow: 10px 15px 5px #cbcbcb;
}
.grid h1 {
font-family: "sans-serif";
background-color: #57636e;
font-size: 60px;
text-align: center;
color: #ffffff;
padding: 2px 0px;
border-radius: 50px;
}
#score {
color: #5A6772;
text-align: center;
font-size: 30px;
}
.grid #question {
font-family: "monospace";
font-size: 30px;
color: #5A6772;
}
.buttons {
margin-top: 30px;
}
#btn0,
#btn1,
#btn2,
#btn3 {
background-color: #778897;
width: 250px;
font-size: 20px;
color: #fff;
border: 1px solid #1D3C6A;
border-radius: 50px;
margin: 10px 40px 10px 0px;
padding: 10px 10px;
}
#btn0:hover,
#btn1:hover,
#btn2:hover,
#btn3:hover {
cursor: pointer;
background-color: #57636e;
}
#btn0:focus,
#btn1:focus,
#btn2:focus,
#btn3:focus {
outline: 0;
}
#progress {
color: #2b2b2b;
font-size: 18px;
}<!DOCTYPE html>
<html>
<head lang = "en">
<meta charset = "UTF-8">
<title>Quiz</title>
<link rel = "stylesheet" type = "text/css" href = "style.css">
</head>
<body>
<div class = "grid">
<div id = "quiz">
<h1>Quiz</h1>
<hr style = "margin-bottom: 20px">
<p id = "question"></p>
<div class = "buttons">
<button id = "btn0"><span id = "choice0"></span></button>
<button id = "btn1"><span id = "choice1"></span></button>
<button id = "btn2"><span id = "choice2"></span></button>
<button id = "btn3"><span id = "choice3"></span></button>
</div>
<hr style = "margin-top: 50px">
<footer>
<p id = "progress">Question x of y</p>
</footer>
</div>
</div>
</body>
</html>У меня есть все, но я не включил их во фрагмент кода
Я понимаю. но создание минимальный воспроизводимый пример значительно упрощает нам поиск решения, подходящего для вашей проблемы.
Я после редактирования кода, так что он дает больше, поэтому я надеюсь, что это поможет. Извините, я новичок в этом!
Пожалуйста, нажмите кнопку [<>] в редакторе, поместите соответствующий код в соответствующие контейнеры и посмотрите, как он запустится.
Готово, фрагменты кода не использовались, поэтому теперь полностью работает
Я раскомментировал некоторые вещи и переместил генерацию викторины в конец после определения прототипа. Теперь это работает.



![Безумие обратных вызовов в javascript [JS]](https://i.imgur.com/WsjO6zJb.png)


Как сказал Йорк, вам необходимо загрузить / поместить изображения на свой сервер или получить их с других URL-адресов.
Затем вам нужно сохранить их (возможно, в questions). В этом примере я использовал imgURL внутри каждого Question.
Затем используйте этот код, чтобы показать изображение:
var element = document.getElementById("question");
element.innerHTML = '<img src=' + quiz.getQuestionIndex().imgURL + '" />'
Я только что отредактировал его там вместе с остальным кодом, который помогает!
Я предполагаю, что вы имеете в виду это - замените изображения заполнителей своими собственными. EncodeURI был создан только потому, что # и ++ являются элементами uri:
var images = {
"CSS" : "https://via.placeholder.com/200x50?text=CSS",
"HTML" : "https://via.placeholder.com/200x50?text=HTML",
"Java" : "https://via.placeholder.com/200x50?text=JAVA",
"C#" : "https://via.placeholder.com/200x50?text=C"+encodeURIComponent("#"),
"C++" : "https://via.placeholder.com/200x50?text=C"+encodeURIComponent("++"),
"C" : "https://via.placeholder.com/200x50?text=C"
}
function populate() {
if (quiz.isEnded()) {
showScores();
} else {
// show question
var element = document.getElementById("question");
element.innerHTML = quiz.getQuestionIndex().text;
// show options
var choices = quiz.getQuestionIndex().choices;
for (var i = 0; i < choices.length; i++) {
var element = document.getElementById("choice" + i);
element.innerHTML = images[choices[i]]? '<img src = "'+images[choices[i]]+'"/>':choices[i];
guess("btn" + i, choices[i]);
}
showProgress();
}
};
function guess(id, guess) {
var button = document.getElementById(id);
button.onclick = function() {
quiz.guess(guess);
populate();
}
};
function showProgress() {
var currentQuestionNumber = quiz.questionIndex + 1;
var element = document.getElementById("progress");
element.innerHTML = "Question " + currentQuestionNumber + " of " + quiz.questions.length;
};
function showScores() {
var gameOverHTML = "<h1>Result</h1>";
gameOverHTML += "<h2 id='score'> Your scores: " + quiz.score + "</h2>";
var element = document.getElementById("quiz");
element.innerHTML = gameOverHTML;
};
// create questions
var questions = [
new Question("<img src='https://via.placeholder.com/200x50?text=OOP' /><br/>Which one is not an object oriented programming language?", ["Java", "C#", "C++", "C"], "C"),
new Question("<img src='https://via.placeholder.com/200x50?text=Web+development' /><br/>Which language is used for styling web pages?", ["HTML", "JQuery", "CSS", "XML"], "CSS"),
new Question("There are ____ main components of object oriented programming.", ["1", "6", "2", "4"], "4"),
new Question("Which language is used for web apps?", ["PHP", "Python", "Javascript", "All"], "All"),
new Question("MVC is a ____.", ["Language", "Library", "Framework", "All"], "Framework")
];
function Question(text, choices, answer) {
this.text = text;
this.choices = choices;
this.answer = answer;
}
Question.prototype.isCorrectAnswer = function(choice) {
return this.answer === choice;
}
function Quiz(questions) {
this.score = 0;
this.questions = questions;
this.questionIndex = 0;
}
Quiz.prototype.getQuestionIndex = function() {
return this.questions[this.questionIndex];
}
Quiz.prototype.guess = function(answer) {
if (this.getQuestionIndex().isCorrectAnswer(answer)) {
this.score++;
}
this.questionIndex++;
}
Quiz.prototype.isEnded = function() {
return this.questionIndex === this.questions.length;
}
// create quiz
var quiz = new Quiz(questions);
// display quiz
populate();body {
background-color: #eeeeee;
}
.grid {
width: 600px;
height: 500px;
margin: 0 auto;
background-color: #fff;
padding: 10px 50px 50px 50px;
border-radius: 50px;
border: 2px solid #cbcbcb;
box-shadow: 10px 15px 5px #cbcbcb;
}
.grid h1 {
font-family: "sans-serif";
background-color: #57636e;
font-size: 60px;
text-align: center;
color: #ffffff;
padding: 2px 0px;
border-radius: 50px;
}
#score {
color: #5A6772;
text-align: center;
font-size: 30px;
}
.grid #question {
font-family: "monospace";
font-size: 30px;
color: #5A6772;
}
.buttons {
margin-top: 30px;
}
#btn0,
#btn1,
#btn2,
#btn3 {
background-color: #778897;
width: 250px;
font-size: 20px;
color: #fff;
border: 1px solid #1D3C6A;
border-radius: 50px;
margin: 10px 40px 10px 0px;
padding: 10px 10px;
}
#btn0:hover,
#btn1:hover,
#btn2:hover,
#btn3:hover {
cursor: pointer;
background-color: #57636e;
}
#btn0:focus,
#btn1:focus,
#btn2:focus,
#btn3:focus {
outline: 0;
}
#progress {
color: #2b2b2b;
font-size: 18px;
}<!DOCTYPE html>
<html>
<head lang = "en">
<meta charset = "UTF-8">
<title>Quiz</title>
<link rel = "stylesheet" type = "text/css" href = "style.css">
</head>
<body>
<div class = "grid">
<div id = "quiz">
<h1>Quiz</h1>
<hr style = "margin-bottom: 20px">
<p id = "question"></p>
<div class = "buttons">
<button id = "btn0"><span id = "choice0"></span></button>
<button id = "btn1"><span id = "choice1"></span></button>
<button id = "btn2"><span id = "choice2"></span></button>
<button id = "btn3"><span id = "choice3"></span></button>
</div>
<hr style = "margin-top: 50px">
<footer>
<p id = "progress">Question x of y</p>
</footer>
</div>
</div>
</body>
</html>Большое спасибо! Как бы я сделал это для вопросов, а не для ответов.
Как это? new Question("<img src = "oop.jpg" /> Which one is not an object oriented programming language?"
Ага! Как мне изменить это на URL-адрес изображения? Я получаю ошибки, когда пытаюсь
Щелкните редактор фрагментов
<>и укажите HTML и сценарий в минимальный воспроизводимый пример - я не вижу, где вы здесь показываете ответы - у вас также нет кода дляQuestion