Change background color using jQuery

前提是你 提交于 2021-02-05 05:35:05

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!