2016-07-02 14 views
0

我是JQuery的新手,我對此有一個非常基本的問題。用JQuery修改某個ID的HTML元素

我有兩個html表格元素,一個id =「needColor」,另一個沒有id。

我想成立一​​個甚至行的背景色上使用id =「needColor」,而不是在桌子上沒有任何標識。

我該如何使用JQuery來做到這一點?

當前代碼如下:

<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> 

感謝。

+0

我在您的代碼中看到一條評論指出:*不要使用(「#needColor」),因爲這會影響除「table」之外的其他元素*。不是這種情況。 ID始終是唯一的 - 您不應該給兩個或更多元素使用相同的ID。 –

+0

另外,你也可以用css做同樣的事情'#needColor tr:even/tr:odd {/ *你的風格* /}' –

+0

該操作令人困惑...首先你想使用'id'因爲你不用它將適用於所有表,然後第二你不想使用'ID',因爲它只適用於一個表?這是哪個? – guradio

回答

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

選擇器的第一部分#needColor獲取具有該id的元素。 td:even表示獲得偶數tr元素。這兩部分之間的空間意味着tr元素應該是第一個元素的後代。

如果你有多個元素id="needColor"那麼你有無效的HTML:ID應該是唯一的,所以如果你需要識別多個元素爲需要顏色,你應該使用一個類而不是ID。但儘管如此,如果你不能改變的HTML出於某種原因,那麼你可以這樣做:

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

注意,雖然你不需要任何的JavaScript/jQuery的這一點,你可以只是CSS做。在你的樣式表:

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

[+](http://stackoverflow.com/a/38156305/227267)1對於CSS,除非需要,否則不要使用腳本。 –

0

試試這個:

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

還是這個(不過,我想上面的建議):

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

他們都將背景顏色設置爲黃色表與ID「needColor」