问题
I am trying to change the background color with jQuery. What am I doing wrong? I know this can be done with CSS a lot easier but I am trying to do it with jQuery.
Link to jsfiddle. I am trying to change the background of "Hi" to yellow.
window.onload=function(){
$('.myClass td').css({'background-color': 'yellow'});
}
<table>
<tr class="myClass">
<td>Hi</td>
</tr>
<tr>
<td>Bye</td>
</tr>
</table>
回答1:
Use document.ready for your JS.
$(document).ready(function(){
$('.myClass td').css({'background-color': 'yellow'});
});
回答2:
Use $(document).ready()
:
$(document).ready(function(){
$('.myClass td').css({'background-color': 'yellow'});
});
See jsfiddle for working example.
回答3:
window.onload
is probably being overwritten by something.
Instead try
$(function(){
$('.myClass td').css({'background-color': 'yellow'});
});
Which is shorthand for $(document).ready
.
Here is a discussion of the difference between the onload
and ready
events.
回答4:
Bind your function to jQuery's document.ready
event:
$(document).ready(function () {
$('.myClass td').css({'background-color': 'yellow'});
});
Or, more concisely:
$(function () {
$('.myClass td').css({'background-color': 'yellow'});
});
回答5:
window.onload=function(){
$('.myClass td').css("background-color", "yellow");
}();
Just added in the (); at the end to invoke it.
http://jsfiddle.net/p2Uwx/5/ <-- updated fiddle
来源:https://stackoverflow.com/questions/18475579/change-background-color-using-jquery