唯一标识HTML表以计算列数

时间:2013-06-09 15:08:47

标签: jquery jquery-selectors count dynamic-columns

我需要将列附加到特定位置的HTML表中。 This topic discusses doing that - 非常方便!我的问题是,下面显示的columnCount()函数无法定位特定的表。它计算HTML中存在的所有TD,这些TD在生成索引值时最终会导致问题。

function countColumn() {
   var colCount = 0;
   $('tr:nth-child(1) td').each(function () {
       if ($(this).attr('colspan')) {
           colCount += +$(this).attr('colspan');
       } else {
           colCount++;
       }
   });
   return colCount;
}

我有两个JS小提琴。

  • One functions因为只有一张表。
  • The second one无效,因为存在两个表。

    第二个小提琴返回无效的colCount值,无法将列放在目标表中。我在选择器上仍然太绿,无法在上下文中应用正确的选择器......我正在慢慢学习这种语言。

编辑 Link to the JSFiddle that has the corrected code.我希望这可以帮助那些正在努力使用选择器语法的其他人!

1 个答案:

答案 0 :(得分:1)

将表格ID作为参数:

function countColumn(tableID) {
   var colCount = 0;
   $('#' + tableID + ' tr:nth-child(1) td').each(function () {
       if ($(this).attr('colspan')) {
           colCount += +$(this).attr('colspan');
       } else {
           colCount++;
       }
   });
   return colCount;
}

您还可以定义一个在选择器上运行的jQuery方法:

$.fn.colCount = function() {
   var colCount = 0;
   $('tr:nth-child(1) td', this).each(function () {
       if ($(this).attr('colspan')) {
           colCount += +$(this).attr('colspan');
       } else {
           colCount++;
       }
   });
   return colCount;
};

然后你可以var count = $("#someTable").colCount();