OnClick change all sibling table rows jQuery
I am try to write a jQuery statement to change the table row that is currently clicked to a different foreground color while making all the sibling table rows the same color. Basically making it look like the clicked row is active. Here's what I have so far, this here works the first time, but on the second time on it never sets all the siblings to the non selected color.
<script type="text/javascript">
function changeRows(currentRow) {
$(currentRow).css('color', 'green'); // change clicked row to active color
$(currentRow).parent().siblings().css('color', 'red'); // change all the rest to non active color
}
</script>开发者_如何转开发
<table>
<tr>
<td onclick="changeRows(this)">123
</td>
</tr>
<tr>
<td onclick="changeRows(this)">1234
</td>
</tr>
<tr>
<td onclick="changeRows(this)">12345
</td>
</tr>
<tr>
<td onclick="changeRows(this)">123456
</td>
</tr>
</table>
It's best to handle this type of stuff through classes rather than popping in ad-hoc css rules.
$("td").click(function(){
$(this).addClass("on").parent().siblings("tr").find("td").removeClass("on");
});
Online demo: http://jsbin.com/ajalu/2/edit
Or you can base it on the TR itself:
$("tr").click(function(){
$(this).addClass("on").siblings("tr").removeClass("on");
});
Online demo: http://jsbin.com/ajalu/3/edit
I would prefer doing this by adding/removing CSS classes rather than setting CSS directly. I think your issue though is that you're setting the css on the column element rather than on the rows themselves. You might want to try something like:
<script type="text/javascript">
function changeRows(currentElem) {
var $currentElem = $(currentElem);
var $currentRow = $currentElem.closest('tr');
var $table = $currentElem.closest('table');
$table.find('tr').removeClass('highlight');
$currentRow.addClass('highlight');
}
</script>
instead of using onclick in your html markup use
If you have an id on each td you could do
$('#td1').click(function() {
$('td').removeClass('.colored');
$(this).addClass('.colored'); // change clicked row to active color
});
精彩评论