【问题标题】:Combining a counter with 2 table classes将计数器与 2 个表类相结合
【发布时间】:2013-02-22 22:38:40
【问题描述】:

当我点击一个单元格进行类测试时,我有一个 *10 的计数器,而当我点击一个用于类害虫的单元格时,我有一个 *20 的计数器。我如何组合这些计数器,使它们都显示在同一个 div 中?它的工作原理就像,假设我单击一个测试单元格,会显示 10 个。如果我单击另一个测试单元格,将显示 20。如果我重新单击一个测试单元格,则会显示 10,因为该单元格将被“停用”。同样适用于害虫细胞,但那将是 20 年代。现在,当我尝试同时单击测试单元和害虫单元时,它不能正确计算。有什么帮助吗?

<table>
<tr>
<td class='test' id='g'><img src='images/Cat.gif'/></td>
<td class='test' id='g'><img src='images/Dog.gif'/></td>
<td class='pest' id='e'><img src='images/Mouse.gif'/></td>
<td class='pest' id='e'><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.length*20);
});
});

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

例如:现在当我点击 1 个测试单元和 1 个害虫单元时,它显示的是 20 而不是 30。

【问题讨论】:

    标签: jquery html counter


    【解决方案1】:

    演示: http://jsfiddle.net/ZjsVB/

    $(document).ready(function() {
        $('td.test, td.pest').click(function() {
            $(this).toggleClass('active');
    
            var testCount = $('td.test.active').length * 10;
            var pestCount = $('td.pest.active').length * 20;
    
            $('#output').text(testCount + pestCount);
        });
    });
    

    【讨论】:

    • 比我的代码简单得多,并且让我明白了一些事情。再次感谢
    • 我正要发布几乎完全相同的代码:jsfiddle.net/3PgGb,然后我看到了你的代码并且有似曾相识的感觉。 +1
    猜你喜欢
    • 2017-10-19
    • 2013-01-20
    • 1970-01-01
    • 2014-10-13
    • 2021-11-11
    • 1970-01-01
    • 1970-01-01
    • 2022-01-17
    • 1970-01-01
    相关资源
    最近更新 更多