开发者

jQuery: Increment variable value based on clicks

I have the following jQuery code:

var letter_a = 0;
var letter_b = 0;
var letter_c = 0;

$(".abc li a").click(function ()
{
    var selected = $(this).hasClass('selected');
    $(this).closest('ul.abc').find('li a').removeClass('selected');
    if (!selected)
    {
        $(this).addClass('selected');
    }

    if ($(this).hasClass("a"))
    {
        letter_a++;
    }
    else if ($(this).hasClass("b"))
    {
        letter_b++;
    }
    else if($(this).hasClass("a"))
    {
        letter_c++;
    }
});

What happens is when a person clicks a li开发者_JAVA百科nk like: <a class="a">Option A</a> it will increment the variable by one and so on and so on. But because users can deselect options and also change their minds, I also need it to decrement if they have chosen a different answer or deselected.

How would I do this?

Thanks


Assuming this is using the same HTML as your other question I think it might be easier to just do a count of all of the selected items every time you select an answer:

var scoreA = 0, scoreB = 0, scoreC = 0;

$(".abc li a").click(function () {
    var t = $(this);
    var ul = t.closest('ul.abc');
    var selected = t.hasClass('selected');
    ul.find('li a').removeClass('selected');
    if (!selected)
        t.addClass('selected');

    calculateScores();
});

function calculateScores()
{
    scoreA = $('a.a.selected').length;
    scoreB = $('a.b.selected').length;
    scoreC = $('a.c.selected').length;

    alert("A: " + scoreA + ", B: " + scoreB + ", C: " + scoreC);
}

http://jsfiddle.net/huW4k/2/


what are you going to do with the totals, I wonder if it would be easier to just get the length of selected boxes

 $(.a.selected).length;
 $(.b.selected).length;
 $(.c.selected).length;


Do it like this:

 var letter_a = 0;
 var letter_b = 0;
 var letter_c = 0;

 $(".abc li a").click(function ()
{
var selected = $(this).hasClass('selected');
$(this).closest('ul.abc').find('li a').removeClass('selected');
if (!selected)
{
    $(this).addClass('selected');
}

if ($(this).hasClass("a"))
{
    letter_a++;
    if(letter_b != 0){
      letter_b--;}

    if(letter_c != 0){
      letter_c--;}
}
else if ($(this).hasClass("b"))
{
    letter_b++;

    if(letter_a != 0){
      letter_a--;}

    if(letter_c != 0){
      letter_c--;}
}
else if($(this).hasClass("a"))
{
    letter_c++;

    if(letter_a != 0){
      letter_a--;}

    if(letter_b != 0){
      letter_b--;}
}
});
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜