简体   繁体   English

使用JQuery修改特定ID的HTML元素

[英]Modify HTML element of certain ID with JQuery

I am new to JQuery and I have a very basic question about this. 我是JQuery的新手,对此我有一个非常基本的问题。

I have two html table elements, one with id="needColor" and another one without id. 我有两个html表格元素,一个带有id =“ needColor”,另一个没有id。

I want to set the background color of an even row on the table with id = "needColor" but not on the table without any id. 我想在id =“ needColor”的上设置偶数行的背景颜色,但在没有任何id的表上不设置背景色。

How can I do this with the JQuery? 如何使用JQuery做到这一点?

The current code is as follows: 当前代码如下:

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"</script>
<script>
$(document).ready(function(){

//tried to add something like these, but I am not sure how it must be written

// this makes all the even row in "all" table to be yellow
$("tr:even").css("background-color", "yellow");

// this will give the whole yellow color of table with id = needColor
$("table[id='needColor']").css("background-color", "yellow"); // do not use ("#needColor") as this will affect other elements than "table"


});
</script>

Thanks. 谢谢。

$("#needColor tr:even").css("background-color", "yellow");

The first part of the selector, #needColor , gets the element with that id. 选择器的第一部分#needColor ,获取具有该ID的元素。 td:even means get the even tr elements. td:even表示获得偶数tr元素。 The space between those two parts means that the tr elements should be descendents of the first element. 这两个部分之间的空间意味着tr元素应该是第一个元素的后代。

If you have more than one element with id="needColor" then you have invalid html: id is supposed to be unique, so if you need to identify multiple elements as needing colour you should use a class rather than id. 如果您具有多个id="needColor"元素,那么您的html无效:id应该是唯一的,因此,如果您需要标识多个需要颜色的元素,则应使用类而不是id。 But still, if you can't change the html for some reason then you can do this: 但是,如果您由于某种原因不能更改html,则可以执行以下操作:

$("table[id='needColor'] tr:even").css("background-color", "yellow");

Note though that you don't need any JavaScript/jQuery for this, you can do it just with CSS. 请注意,尽管您不需要任何JavaScript / jQuery,但只需使用CSS即可。 In your stylesheet: 在样式表中:

table[id='needColor'] tr:nth-child(even) {
  background-color: yellow;
}

Try this: 尝试这个:

$("#needColor tr:even").css("background-color", "yellow");

Or this (But I would suggest above): 或这个(但我会在上面建议):

$("table[id='needColor'] tr:even").css("background-color", "yellow");

Both of them will set background color to yellow of table with id "needColor" 他们两个都将背景色设置为ID为“ needColor”的表格的黄色

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

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