Jquery 计算html表中突出显示的单元格

Jquery 计算html表中突出显示的单元格,jquery,Jquery,我试图计算每行中单击的选定单元格的数量,并在表格右侧的单元格中显示计数 守则: $function{ $'td'。单击函数{ $this.toggleClassselectedCell; }; }; 函数更新计数{ $'.t输出'.html; $'.row'.eachfunctionindex{ $'.tdoutput.html$'.tdoutput.html+$this.find.selectedCell.length+'selectedcells'; }; } $'.td'。单击函数{ /

我试图计算每行中单击的选定单元格的数量,并在表格右侧的单元格中显示计数

守则:

$function{ $'td'。单击函数{ $this.toggleClassselectedCell; }; }; 函数更新计数{ $'.t输出'.html; $'.row'.eachfunctionindex{ $'.tdoutput.html$'.tdoutput.html+$this.find.selectedCell.length+'selectedcells'; }; } $'.td'。单击函数{ //添加或删除类 $this.toggleClass'selectedCell'; //更新类计数 更新统计数字; }; //在domready上运行该函数 $function{ 更新统计数字; }; .选定的单元格{ 背景颜色:绿色; } 1. 2. 3. 4. 5. 6. 7. 1. 2. 3. 4. 5. 6. 7. 试试这个代码

添加更新计数;在脚本的第一个代码中删除。td单击代码

$function{ $'td'。单击函数{ $this.toggleClassselectedCell; 更新\u计数;//在此处添加 }; }; 函数更新计数{ $'.t输出'.html; $'.row'.eachfunctionindex{ //console.log$this.find'.selectedCell'.length,index,'test'; $'.tdoutput.html$'.tdoutput.html+$this.find.selectedCell.length+'selectedcells'; }; } //在domready上运行该函数 $function{ 更新统计数字; }; .选定的单元格{ 背景颜色:绿色; } 1. 2. 3. 4. 5. 6. 7. 1. 2. 3. 4. 5. 6. 7.
我想你正在寻找这样的东西:

使用td和respect以及tr和find来实现此行为

$function{ $table tr.eachfunction{ 更新_计算$this; }; }; 函数更新\u计数$tr{ var count=$tr.find'.selectedCell'.length; $tr.find'.tdoutput'.htmlcount+已选中; } $'td'。单击函数{ //添加或删除类 $this.toggleClass'selectedCell'; //更新类计数 更新\u counts$this.closesttr; }; .选定的单元格{ 背景颜色:绿色; } 1. 2. 3. 4. 5. 6. 7. 1. 2. 3. 4. 5. 6. 7.
你很接近。您需要使用上下文参数或$this.find.tdoutput在rows循环中找到与特定行相关的$'.tdoutput'实例的上下文

函数更新计数{ $'.row'.eachfunctionindex{ $'.tdoutput',this.html$this.find'.selectedCell'.length+'selectedcells'; //^^^^仅在此行中 }; } //在domready上运行该函数 $function{ 更新统计数字; $'td'。单击函数{ //添加或删除类 $this.toggleClass'selectedCell'; //更新类计数 更新统计数字; }; }; .选定的单元格{ 背景颜色:绿色; } td{padding:5px} 1. 2. 3. 4. 5. 6. 7. 1. 2. 3. 4. 5. 6. 7.
这是工作小提琴。我希望我能设法帮助你。仅对脚本进行了轻微更改

<script>
$( function() {
  $('td').click( function() {
    $(this).toggleClass("selectedCell");
    var numItems = $('.selectedCell').length
    $('.tdoutput').html(numItems +" Selected")
    });
});
</script>
将您的JS更改为:

function update_counts()
{
    // Clear output
    $('.tdoutput').html('');
    // Each rows,
     $('.row').each(function(index,rowObject){
         // Count has .selectedCell in this row
         var count = $(rowObject).find('td.selectedCell').length;
         // Write to this row output.
         $(rowObject).find('td.tdoutput').html( count + ' selected cells ');
     });  
}

$('td').click(function(){
  // Add or remove class
  $(this).toggleClass('selectedCell');

  // Update the class counts
  update_counts();
}); 



// Run the function on domready 
$(function(){
   update_counts();
});

谢谢大家的回答。怀疑这是预期的行为您怀疑@charlietfl$'.tdoutput.html总是只获取第一行的值,并且您正在使所有行呈现samei只有更新用户问题,而不是尝试最佳方式代码,因为用户混淆了新代码,不了解如何工作@查利特夫。所以第一件事是用户如何在路上得到他的问题答案,而不是我们在每一行中单击的单元格。。。不复杂