我的问题是,我希望仅在用户点击div
并且div
没有上课selected
或wrong
时才添加分数它。简单来说,如果div
上已经存在类,我就不希望添加分数。现在它工作正常,但如果用户一直点击相同的div
,它会不断添加分数。
对不完整的代码感到抱歉(这是很长的jQuery游戏的一部分),但任何指导都会有所帮助!
JQuery的
if ($(this).attr("selected") == "selected") {
$(this).addClass("selected");
var score = parseInt($("#score").html());
score += 20;
$("#score").html(score);
} else {
$(this).addClass("wrong");
var score = parseInt($("#score").html());
score -= 10;
$("#score").html(score);
}
答案 0 :(得分:1)
您可以使用.hasClass()
,如下所示:
if(!$(this).hasClass('wrong') && !$(this).hasClass('selected'))
{
if ($(this).attr("selected") == "selected") {
$(this).addClass("selected");
var score = parseInt($("#score").html());
score += 20;
$("#score").html(score);
} else {
$(this).addClass("wrong");
var score = parseInt($("#score").html());
score -= 10;
$("#score").html(score);
}
}
答案 1 :(得分:0)
使用removeClass删除已存在的内容:
if ($(this).attr("selected") == "selected") {
$(this).removeClass();// remove already added class if there
$(this).addClass("selected");
var score = parseInt($("#score").html());
score += 20;
$("#score").html(score);
} else {
$(this).removeClass();// remove already added class if there
$(this).addClass("wrong");
var score = parseInt($("#score").html());
score -= 10;
$("#score").html(score);
}