问题
I looked at other similar questions but it did not help me. I want to change the table row background color when I select radio button to blue. When I click another radio button I want the other to change back to normal and the one I click to change to blue. As of now, when I select a radio button it just act like a hover and make the row blue as soon as I move the mouse away it goes back to its original color. I want to be able to hover and click:
<script>
$(document).ready(function () {
$("tr").not(':first').hover(
function () {
$(this).css("background","lightblue");
},
function () {
$(this).css("background","");
}
);
$('input:radio').change(function () {
$(this).closest('tr').siblings().css('background-color', 'white')
.end().css('background-color', 'darkblue');
});
});
</script>
回答1:
$('input:radio').change(function () {
var parentTr = $(this).closest('tr');
parentTr.siblings().css('background-color', 'white');
parentTr.css('background-color', 'darkblue');
});
You can also use end
:
$('input:radio').change(function () {
$(this).closest('tr').siblings().css('background-color', 'white')
.end().css('background-color', 'darkblue');
});
But it's usually harder to read and maintain.
- Note that you better use css class instead of change the css inline.
回答2:
Try this:
<!DOCTYPE html>
<html lang="en">
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js" type="text/javascript"></script>
</head>
<body>
<table>
<tr><td><input class="rad" type="radio" name="blah" value="1"/>One</td></tr>
<tr><td><input class="rad" type="radio" name="blah" value="2"/>Two</td></tr>
<tr><td><input class="rad" type="radio" name="blah" value="3"/>Three</td></tr>
</table>
</body>
</html>
<script type="text/javascript">
$("tr").not(':first').hover(
function () {
if($(this).css("background-color") != 'darkblue'){
$(this).css("background","lightblue");
}
},
function () {
if($(this).css("background-color") != 'darkblue'){
$(this).css("background","");
}
}
);
$(".rad").unbind("click").click(function(){
$('tr').css('background-color', 'white');
$(this).closest('tr').css('background-color', 'darkblue');
});
</script>
来源:https://stackoverflow.com/questions/10690898/radio-button-change-table-row-background-color-when-selected-and-go-back-to-norm