Javascript jQuery区域元素只添加一次
正在编写一个用于练习jquery的小游戏 我制作的脚本将区域添加到html映射元素。 但它只增加了一个区域,我不明白为什么 脚本功能Javascript jQuery区域元素只添加一次,javascript,jquery,Javascript,Jquery,正在编写一个用于练习jquery的小游戏 我制作的脚本将区域添加到html映射元素。 但它只增加了一个区域,我不明白为什么 脚本功能 function renderQuestion(question){ // load correct and incorrect areas question.$correctArea.appendTo($questionMap); question.$incorrectArea.appendTo($questionMap);
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();
});
游戏在线网址为:
正如您所注意到的,在提问时,它会用正确的区域加载第一个正确的问题。
单击正确答案后,将加载下一个问题,但不会替换新区域。
有人看到了吗
编辑
已更改函数renderQuestion:
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){
// 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)
),它应该可以工作。在开始添加问题图之前清空问题图
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
});
}
这似乎只对一个区域有效,我需要它们在同一个DIV上连续调用.html()
两次将覆盖第一个区域。你知道我如何添加/替换这两个区域吗?你认为你能为你的问题找到更好的标题吗?标题不好?我来换那个!对不起