当表包含列跨越单元格时,使用jQuery查找列索引 [英] Finding column index using jQuery when table contains column-spanning cells

查看:97
本文介绍了当表包含列跨越单元格时,使用jQuery查找列索引的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用jQuery,如何在下面的示例表中找到任意表格单元格的列索引,以便跨越多列的单元格具有多个索引?

Using jQuery, how can I find the column index of an arbitrary table cell in the example table below, such that cells spanning multiple columns have multiple indexes?

<table>
  <tbody>
    <tr>
      <td>One</td>
      <td>Two</td>
      <td id="example1">Three</td>
      <td>Four</td>
      <td>Five</td>
      <td>Six</td>
    </tr>
    <tr>
      <td colspan="2">One</td>
      <td colspan="2">Two</td>
      <td colspan="2" id="example2">Three</td>
    </tr>
    <tr>
      <td>One</td>
      <td>Two</td>
      <td>Three</td>
      <td>Four</td>
      <td>Five</td>
      <td>Six</td>
    </tr>
  </tbody>
</table>



jQuery



jQuery

var cell = $("#example1");
var example1ColIndex = cell.parent("tr").children().index(cell);
// == 2. This is fine.

cell = $("#example2");
var example2ColumnIndex = cell.parent("tr").children().index(cell);
// == 2. It should be 4 (or 5, but I only need the lowest). How can I do this?


推荐答案

这是一个可以计算'noncolspan'指数的插件。

Here's a plugin which can calculate the 'noncolspan' index.

$(document).ready(
        function()
        {
        console.log($('#example2').getNonColSpanIndex()); //logs 4
        console.log($('#example1').getNonColSpanIndex()); //logs 2
    }

);

$.fn.getNonColSpanIndex = function() {
    if(! $(this).is('td') && ! $(this).is('th'))
        return -1;

    var allCells = this.parent('tr').children();
    var normalIndex = allCells.index(this);
    var nonColSpanIndex = 0;

    allCells.each(
        function(i, item)
        {
            if(i == normalIndex)
                return false;

            var colspan = $(this).attr('colspan');
            colspan = colspan ? parseInt(colspan) : 1;
            nonColSpanIndex += colspan;
        }
    );

    return nonColSpanIndex;
};

这篇关于当表包含列跨越单元格时,使用jQuery查找列索引的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆