制作一个练习jquery的小游戏。
我制作的脚本将区域添加到html地图元素中。但它只添加了一次区域,我不明白为什么
脚本函数
function renderQuestion(question){
// load correct and incorrect areas
question.$correctArea.appendTo($questionMap);
question.$incorrectArea.appendTo($questionMap);
// set question background image
$questionImage.attr({
src: question.backgroundImage
});
}
function onCorrect(){
score++;
loadNextQuestion();
}
function onIncorrect(){
$questionImage.attr({
src: "../img/items/fail.png"
});
}
function loadNextQuestion(){
renderQuestion(questions[questionIndex]);
questionIndex++;
}
// load first question
loadNextQuestion();
// clicks
$('.correct-area').click(function(){
onCorrect();
});
$('.incorrect-area').click(function(){
onIncorrect();
});
游戏在线网址:http://i333180.iris.fhict.nl/demo/pages/index.php
正如你所注意到的,在问题中,它会将第一个问题加载到正确的区域。单击正确答案后,将加载下一个问题,但不会替换新区域。有人看到了吗?
编辑更改了函数render问题:
function renderQuestion(question){
// load correct and incorrect areas
$questionMap.html(question.$incorrectArea);
$questionMap.html(question.$correctArea);
// set question background image
$questionImage.attr({
src: question.backgroundImage
});
// clicks
$('.correct-area').on('click', onCorrect);
$('.incorrect-area').on('click', onIncorrect);
}
点击的方式是正确的,并且添加了正确的区域。但通过使用.html,它只添加了最后一个区域,我需要它们都是
在开始追加问题图之前清空问题图。
function renderQuestion(question){
// Clear out old questions
$questionMap.empty();
// load correct and incorrect areas
question.$correctArea.appendTo($questionMap);
question.$incorrectArea.appendTo($questionMap);
// set question background image
$questionImage.attr({
src: question.backgroundImage
});
}
function renderQuestion(question){
// load correct and incorrect areas
$questionMap.html(question.$correctArea)
$questionMap.append(question.$incorrectArea)
// set question background image
$questionImage.attr({
src: question.backgroundImage
});
}
使用html()
方法替换内容,而不仅仅是将新内容附加到底部。我不确定您的$questionMap
是否是jQuery对象,如果不是,请像包装其他对象一样包装它($($questionMap)
(,它应该可以工作。