简体   繁体   中英

jquery: Change the background-colour of a column if its header has a class

I have the following jQuery that I'm trying to use to change the background colour of a column where its header has a class.

So for example:

$('th').each(function (i) {

            if ($(this).hasClass('headerSortUp') || $(this).hasClass('headerSortDown')) {
                sortIndex = $(this).index();
            }
            $('tr').each(function () {
                $('td:eq(' + sortIndex + ')').css('background-color', 'orange');
            });

        });

So if I had a table like:

<table>
<tr>
    <th class="headerSortDown">Header</th>
    <th>Header</th>
    <th>Header</th>
    <th>Header</th>
    <th>Header</th>
</tr>
<tr>
    <td>Text</td>
    <td>Text</td>
    <td>Text</td>
    <td>Text</td>
    <td>Text</td>
</tr>
<tr>
    <td>Text</td>
    <td>Text</td>
    <td>Text</td>
    <td>Text</td>
    <td>Text</td>
</tr>
<tr>
    <td>Text</td>
    <td>Text</td>
    <td>Text</td>
    <td>Text</td>
    <td>Text</td>
</tr>
</table>

So in this example the whole first column should have a bg of orange. However it's not working... Any ideas what I have done wrong? Thanks

您忘记指定上下文

$('td:eq(' + sortIndex + ')', this).css('background-color', 'orange');

Try changing sortIndex = $(this).index(); to sortIndex =i; and
$('td:eq(' + sortIndex + ')').css('background-color', 'orange'); to

$('td:eq(' + sortIndex + ')',$(this)).css('background-color', 'orange'); to select td 's withing the tr

There's no need to iterate over the <th> elements - a selector can pick out just the ones with the right classes.

You can then use .index() to find their column value, and :nth-child() to select every <td> in that column in one go:

$('.headerSortUp, .headerSortDown').each(function() {
    var n = $(this).index() + 1;
    $('td:nth-child(' + n + ')').css('background-color', 'orange');
});

Working demo at http://jsfiddle.net/jNsF4/

[I note also that the original code has a logic error - the code to change the colours should be inside the if { ... } block, not outside it].

There's probably a better selector that causes lesser iterations

var sortIndex;

$('th').each(function (i) {

            if ($(this).hasClass('headerSortUp') || $(this).hasClass('headerSortDown')) {
                sortIndex = $(this).index();
            }
    });


$('td:nth-child(' +sortIndex+1+')').css('background-color', 'orange');

You can check the fiddle here http://jsfiddle.net/ryan_s/nZr9G/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM