我正在制作一个简单的危险游戏,而我的on.click根本没有触发。我试图仅当div包含变量答案中包含的特定文本时,才使div on click触发。
<h1 id="question">
</h1>
<div id="answer0">.</div>
<div id="answer1">.</div>
<div id="answer2">.</div>
<div id="answer3">.</div>
var game = {
correct: 0,
questions: [
"Where was bread invented?",
"What color is the Whitehouse?",
"Where is the Eiffel Tower?",
"What is the capital of Texas?"
],
answers: [
["Italy", "Japan", "Egypt", "Canada"],
["White", "Black", "Green", "Purple"],
["England", "France", "Germany", "Bulgaria"],
["Dallas", "Austin", "Houston", "Atlanta"]
],
answer: ["Egypt", "White", "France", "Dallas"]
};
console.log(game.answer[0])
$('#question').text(game.questions[0]);
$('#answer0').text(game.answers[0][0]);
$('#answer1').text(game.answers[0][1]);
$('#answer2').text(game.answers[0][2]);
$('#answer3').text(game.answers[0][3]);
$( "#answer0" ).on( "click", function() {
if ($('#answer0:contains(game.answer[0])').length) {
alert("Correct!");
game.correct++;
}
});
$( "#answer1" ).on( "click", function() {
if ($('#answer1:contains(game.answer[0])').length) {
alert("Correct!");
game.correct++;
}
});
$( "#answer2" ).on( "click", function() {
if ($('#answer2:contains(game.answer[0])').length) {
alert("Correct!");
game.correct++;
}
});
$( "#answer3" ).on( "click", function() {
if ($('#answer3:contains(game.answer[0])').length) {
alert("Correct!");
game.correct++;
}
});
在这种情况下,当我单击“埃及”时,它应该会触发,但不是。
答案 0 :(得分:1)
您似乎有两个迫在眉睫的问题:
if ($('#answer0:contains(game.answer[0])').length) {
在这里,您正在寻找一个字面上包含文本game.answer[0]
的元素。您可能想使用该变量的实际值,因此可以执行以下操作:
if ($(`#answer0:contains('${game.answer[0]}')`).length) {
这用反引号(而不是单引号)将字符串引起来,因此您可以使用${variable}
对字符串内部的变量进行插值。
第二,您总是在每个answer[0]
语句中查找if
,例如,您可能想使用正确的索引
if ($(`#answer1:contains('${game.answer[1]}')`).length) {
您还错误地认为点击“不会触发”。它们正在触发,但是没有满足您的if
语句条件。使用console.log()
添加一些日志记录可以帮助您了解将来的情况。
答案 1 :(得分:0)
只需更改代码即可正常工作。或使用字符串文字
if ($('#answer0:contains('+game.answer[0]+')').length) {
alert("Correct!");
game.correct++;
}