如何使用jquery查找哪个孩子具有表的特定类

How to find which th child has the particular class for a table using jquery?

本文关键字:孩子 jquery 何使用 查找      更新时间:2023-09-26

如何使用jquery找到哪个孩子对带有"正常排序表"类的表具有"nosort"类?我想用"nosort"类提醒列号。

<table class="normal-sort-table">
    <thead>
        <tr>
            <th>#</th>
            <th>First Name</th>
            <th>Last Name</th>
            <th class="nosort">Username</th>
        </tr>
    </thead>
    <tbody>
        <tr>
            <td>1</td>
            <td>Mark</td>
            <td>Otto</td>
            <td>mark246</td>
        </tr>
    </tbody>
</table>
<script>
$( document ).ready(function() {
    if ( $('.normal-sort-table tr th').hasClass( "nosort" ) ) {alert( 'column-number-with-nosort-class-alert-here' )}

})
</script>

你可以使用 jq .index() 方法:

$('.normal-sort-table tr th.nosort').index()
alert($("th").index($(".nosort")));

如果你想精确列号,那么你已经写

alert($('th.nosort').index()+1);

因为索引从零开始。

alert($('th.nosort').index());

alert($('th.nosort').index()+1);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<table class="normal-sort-table">
        <thead>
            <tr>
                <th>#</th>
                <th>First Name</th>
                <th>Last Name</th>
                <th class="nosort">Username</th>
            </tr>
        </thead>
        <tbody>
            <tr>
                <td>1</td>
                <td>Mark</td>
                <td>Otto</td>
                <td>mark246</td>
            </tr>
        </tbody>
    </table>