Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/jquery/68.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Jquery 仅当div不';我没有这方面的课_Jquery_Class_If Statement - Fatal编程技术网

Jquery 仅当div不';我没有这方面的课

Jquery 仅当div不';我没有这方面的课,jquery,class,if-statement,Jquery,Class,If Statement,我的问题是,我只想在用户单击div并且div没有选择class或错误时添加分数。简单地说,如果类已经存在于div中,我不希望添加分数。现在,它工作正常,但如果用户继续单击相同的div,它会不断增加分数 很抱歉代码不完整(这是相当长的jQuery游戏的一部分),但是任何指导都会很有帮助 JQuery if ($(this).attr("selected") == "selected") { $(this).addClass("selected"); var score = pars

我的问题是,我只想在用户单击
div
并且
div
没有选择class
错误时添加分数。简单地说,如果类已经存在于
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);
}

使用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);
}

您可以使用
.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);
  }
}

很好:)非常感谢!当我离开时,我会接受的can@imbondbaby....just根据您的要求,检查您是否需要
|
&&
条件。