2014-09-27 41 views
0

我的問題是我只希望在用戶點擊divdiv沒有課程selectedwrong就可以添加分數。簡而言之,如果div中的課程已存在,我不希望添加分數。現在它可以正常工作,但如果用戶不斷點擊相同的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); 
} 

回答

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); 
    } 
} 
+0

工作得很好:)謝謝你這麼多!將接受它,當我可以 – imbondbaby 2014-09-27 16:19:30

+0

你的歡迎.. !!!! .. @ imbondbaby – 2014-09-27 16:21:57

+1

@imbondbaby ....只是檢查你是否希望''''或'&&'條件根據您的要求。 – 2014-09-27 16:27:18

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