【发布时间】:2017-10-12 04:50:24
【问题描述】:
我正在尝试为“简单”的 jQuery quiz [Fiddle here] 开发逻辑。问题是,问题路径有些动态,会产生树状结构。
例如,第一个问题是关于宠物的:狗、猫还是鸟?如果你选择狗,它会问什么品种的狗。如果您选择猫,它会询问什么品种的猫。等等,然后深入研究(“这个特定品种的狗是什么颜色的狗?”)
我遇到的问题是第三组问题。我无法让颜色问题适用于任何一只狗。事实上,点击处理程序甚至不会触发。谁能告诉我我在哪里搞砸了?
提前谢谢你。
var questions = [{
"text": "What's your favorite pet?",
"choices": [
{
"label": "Dog",
"path": 1
},
{
"label": "Cat",
"path": 2
},
{
"label": "Bird",
"path": 3
},
]
}, {
"text": "What breed of dog?", //1 a
"choices": [
{
"label": "Golden Retriever",
"path": 4
},
{
"label": "Labrador",
"path": 5
},
{
"label": "Poodle",
"path": 6
},
]
}, {
"text": "What breed of cat?", //1 b
"choices": [
{
"label": "Siamese",
"path": 4
},
{
"label": "Persian",
"path": 4
},
{
"label": "Tortie",
"path": 4
},
]
}, {
"text": "What breed of bird?", //1 c
"choices": [
{
"label": "Bluebird",
"path": 4
},
{
"label": "Robin",
"path": 4
},
{
"label": "Parrot",
"path": 4
},
]
}, {
"text": "What color Golden Retriever?", //1 a i
"choices": [
{
"label": "Golden",
"path": 4
},
{
"label": "Sandy",
"path": 4
},
{
"label": "Blonde",
"path": 4
},
]
}, {
"text": "What color Labrador?", //1 b i
"choices": [
{
"label": "Black",
"path": 4
},
{
"label": "Chocolate",
"path": 4
},
{
"label": "Tan",
"path": 4
},
]
}, {
"text": "What color Poodle?", //1 c i
"choices": [
{
"label": "Ugly",
"path": 4
},
{
"label": "Uglier",
"path": 4
},
{
"label": "Ugliest",
"path": 4
},
]
}];
var currentQuestion = 0,
quizComplete = false;
$(document).ready(function() {
updateQuestion();
if (!quizComplete) {
$('.choice').on('click', function() {
value = $(this).attr('value');
currentQuestion = value;
if (currentQuestion < questions.length) {
updateQuestion();
} else {
quizComplete = true;
}
});
}
});
function updateQuestion() {
var question = questions[currentQuestion].text;
var questionText = $(document).find(".container > .question");
var choiceList = $(document).find(".container > .choices");
var numChoices = questions[currentQuestion].choices.length;
// Set question text
$(questionText).text(question);
// Clear current choices and update with new ones
$(".choice").remove();
var choice, path;
for (i = 0; i < numChoices; i++) {
choice = questions[currentQuestion].choices[i].label;
path = questions[currentQuestion].choices[i].path;
$('<div class="choice" value=' + path + '>' + choice + '</div>').appendTo(choiceList);
}
}
【问题讨论】:
-
当列表被重新创建时,点击监听器被移除(这是构建新列表的副作用)。尝试包装你的 $('.choice').on('click', function() {...});'在一个函数中,然后在需要时调用该函数。
标签: javascript jquery html css arrays