Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
304 views
in Technique[技术] by (71.8m points)

javascript - Highlighting the clicked row of a striped HTML table

Here's an example of my problem on jsFiddle.

I have a table with striped rows imposed by using tr:nth-child(odd) in the CSS, as is done in Twitter Bootstrap for the table-striped class. I want to highlight the most recent clicked row of that table. I do that with the following Javascript:

$('#mytable tbody tr').live('click', function(event) {
    $clicked_tr = $(this);
    $clicked_tr.parent().children().each(function() {
        $(this).removeClass('highlight')
    });
    $clicked_tr.addClass('highlight');
});

That code works fine in a table without striped rows. But with striped rows, the background color of the highlight class won't override the background color of the table-striped class. Why is that? And how can I make it work?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

http://jsfiddle.net/iambriansreed/xu2AH/9/

.table-striped class

.table-striped tbody tr.highlight td { background-color: red; }

... and cleaner jQuery:

$('#mytable tbody tr').live('click', function(event) {
    $(this).addClass('highlight').siblings().removeClass('highlight');
});?

Update: .live() has since been deprecated. Use .on().

$('#mytable').on('click', 'tbody tr', function(event) {
    $(this).addClass('highlight').siblings().removeClass('highlight');
});?

Fixed: http://jsfiddle.net/iambriansreed/xu2AH/127/


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

56.9k users

...