2013-02-22 59 views
0

我在每个单元格中都有一个带有id值和图像的表格。 到目前为止,我的代码在用户单击该单元格时显示单元ID。当用户再次点击同一个单元时,它也'取消显示'该ID。我现在要做的是将数字10分配给我的表类,这样当你点击单元格时,它将显示10,或者如果你点击2个单元格,它将显示20,但是如果你点击其中一个细胞再次减去10.我希望这很容易理解。使用父单元格值进行基本数学运算

这里是我到目前为止的代码: HTML:

<table> 
<tr> 
<td class='test' id='1'><img src='images/Dog.gif'/></td> 
<td class='test' id='2'><img src='images/Cat.gif'/></td> 
<td class='test' id='3'><img src='images/Mouse.gif'/></td> 
<td class='test' id='4'><img src='images/Human.gif'/></td> 
</tr> 
</table> 

JS:

$(document).ready(function() { 
var clicked = []; 
$('td.test').click(function() { 
    var found = clicked.indexOf(this.id);  
    if(found !== -1) { 
     clicked.splice(found, 1);  
    } else { 
     clicked.push(this.id); 
    } 
    $('#output').text(clicked.join(',')); 
}); 
}); 
+0

以防万一我不够清楚。任何具有“测试”级别的值都将具有值10 – user182 2013-02-22 20:55:10

+0

'clicked.length * 10'? – undefined 2013-02-22 20:57:31

回答

1

我不能完全肯定我理解你,但是这是它:

$('#output').text(clicked.length*10); 
+0

是的,虽然这不显示单元ID。无论如何谢谢 – user182 2013-02-22 20:59:28

+0

你能用一个你想要输出看起来像什么的例子来更新你的问题吗? – Barmar 2013-02-22 21:00:34

+0

其实男人,我可以从中得到它。 再次感谢:D – user182 2013-02-22 21:01:59

0

这应该很简单。请尝试以下内容

var score = 0; 

    $('td.test').click(function() { 
     var $this = $(this); 
     if (!$this.hasClass('clicked')) { 
      $this.addClass('clicked'); 
      score += 10; 
     } else { 
      $this.removeClass('clicked'); 
      score -= 10; 
     } 
     $('#output').text(score); 
    }); 
相关问题