简体   繁体   English

HTML:使用jquery的背景颜色?

[英]HTML: Background color using jquery?

HTML: HTML:

<table border="1"style="width:500px" id="table2">
  <tr>
    <th>Firstname</th>
    <th>Lastname</th> 
    <th>grades</th>
  </tr>
  <tr>
    <td>riddhi</td>
    <td>bhatt</td>
    <td>50</td>
  </tr>
  <tr>
    <td>sneh</td>
    <td>pandya</td>
    <td>55</td>
  </tr>
  <tr>
    <td>ankit</td>
    <td>purani</td>
    <td>60</td>
  </tr>
</table>

I want to add a background color in odd rows of table. 我想在表格的奇数行中添加背景色。

JQuery: JQuery的:

$(document).ready(function(){

    $("#table2 > tr:odd").css("background-color","blue");
});

I am new in HTML and jQuery, please suggest me so that I can proceed... 我是HTML和jQuery的新手,请建议我,以便我可以继续...

Use this , 用这个 ,

$(document).ready(function(){

    $("#table2 tr:odd").css("background-color","blue");
});

Demo Fiddle 演示小提琴

> won't work here - Reference >在这里不起作用- 参考


The table hierarcy is table > tbody > tr > td , so in that case, try this, 表层次结构为table > tbody > tr > td ,因此在这种情况下,请尝试此操作,

 $("#table2 > tbody > tr:odd").css("background-color","blue");

Demo 演示

Try this 尝试这个

$("#table2 tr:odd").css("background-color","blue");

DEMO DEMO

tbody, thead and tfoot is rendered by html so you need to use #table2 > tbody > tr:odd,#table2 > thead > tr:odd,#table2 > tfoot > tr:odd as a selector to make it work but you have no sense to use odd here. tbody,thead和tfoot由html渲染,因此您需要使用#table2 > tbody > tr:odd,#table2 > thead > tr:odd,#table2 > tfoot > tr:odd作为选择器,以使其起作用,但是在这里使用奇数没有意义。 So simple if you just remove > then it will be fine: 如此简单,如果您删除>那么就可以了:

$("#table2 tr:odd").css("background-color","blue");

As others said, 正如其他人所说,

$("#table2 tr:odd")

will select ALL of the odd tr's inside table2, it'll work for a simple table. 将在table2中选择所有奇数tr,它将用于简单表。 But if you want to for example put a table inside table2, it will select the trs of the second table too, because they're also inside table2 但是,如果要在table2内放置一个表,它也会选择第二个表的trs,因为它们也在table2内

if you want to select only the tr's from table2, but not the ones of a table inside table2, you would use 如果您只想从table2中选择tr,而不是table2中的一个表,则可以使用

$("#table2>tbody>tr:odd")

which selects only the direct tr children of the direct tbody children of table2 仅选择table2的直接tbody子项的直接tr子项

如果以上方法均无效,请尝试将$更改为jQuery,它将起作用。

It works fine: http://jsbin.com/caxahube/1/edit 它工作正常: http : //jsbin.com/caxahube/1/edit

$(document).ready(function(){

  $('table>tbody>tr:odd').css('background-color', 'blue');

});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM