如何用jQuery找到HTML表的列號

[英]how to find column number of HTML table with jQuery


I want to find out the column number that a td belongs to using jQuery.

我想找到td屬於jQuery的列號。

For example:

例如:

<table>
    <tr>
        <td>Row1, Column1</td>
        <td>Row1, Column2</td>
    </tr>
    <tr class="totalRow">
        <td>Row2, Column1</td>
        <td class="columnChild">Row2, Column2</td>
    </tr>
</table>

I want to find the column number for the cell with a class of columnChild. I know that it is the second child of .totalRow, and is the second column in the table, but how do I find this?

我想找到具有columnChild類的單元格的列號。我知道它是。totalrow的第二個子元素,並且是表中的第二列,但是我如何找到它呢?

Eventually what I want to achieve is to add this to an array so I could have to columns with a class of columnChild and add these to the array, so I can then run a function for each row of a table on the second child.

最后,我想要實現的是將它添加到一個數組中,這樣我就可以有一個columnChild類的列並將它們添加到這個數組中,這樣我就可以在第二個子代上為每個表的行運行一個函數。

I've tried writing this several times, but I'm hitting a bit of coders block so any help would be greatly appreciated. If you guys require any more info, let me know and I'll provide what I can.

我已經試過寫幾次了,但是我遇到了一些代碼塊,所以我非常感謝您的幫助。如果你們需要更多的信息,請告訴我,我會盡我所能提供。

2 个解决方案

#1


11  

To get the index of the td in the tr, you can simply use

要在tr中獲取td的索引,只需使用

var index = $('.columnChild').index();

If you have several cells with this class and you want their index in an array (I'm not sure I understand the second question starting with "Eventually"), you can do

如果您有幾個單元格具有這個類,並且您希望它們的索引在一個數組中(我不確定我是否理解以“最終”開頭的第二個問題),您可以這樣做

var indexes = $('.columnChild').map(function(){return $(this).index()});

#2


0  

so I can then run a function for each row of a table on the second child.

因此,我可以為第二個子項上表的每一行運行一個函數。

This will give you an array of td elements with class .columnChild (within tr elements with class totalRow).

這將為您提供一個帶有. columnchild類的td元素數組(在帶有類totalRow的tr元素中)。

$(".totalRow .columnChild")

this will allow to iterate through the array

 $(".totalRow .columnChild")

 .each(function (index, element)
{

  // element is the tr element

  // your function
});

Hope this helped.

希望這個有幫助。


注意!

本站翻译的文章,版权归属于本站,未经许可禁止转摘,转摘请注明本文地址:https://www.itdaan.com/blog/2013/01/04/b2261e54351a4f21a92d8e8167fddffb.html



 
  © 2014-2022 ITdaan.com 联系我们: