2013-03-20 46 views
0

這裏是我的代碼:jQuery是否支持將CSS應用於新創建的元素?

<script type="text/javascript"> 
$(function(){ 
    $("input[type='button']").click(function(){ 
     $("#table tbody").append($("<tr>").append($("<td>").text("new"))); 
    }); 

      /*double-color effect*/ 
    $("#table tbody tr:even").css({"background":"lightgray"}); 
    $("#table tbody tr:odd").css({"background":"white"}); 
}); 
</script> 
</head> 
<body> 
<input type="button" value="click" /> 
<table id="table"> 
    <tbody> 
     <tr><td>hello</td></tr> 
     <tr><td>world</td></tr> 
     <tr><td>I am here</td></tr> 
    </tbody> 
</table> 
</body> 

我想新創建的tr元素也具有雙色效果,但他們不這樣做,我想知道是否jQuery的可以支持動態應用CSS,就像live()on()方法嗎? 而且我還可以用nth-child選擇,這樣的代碼:

tr:nth-child(odd) 
{ 
    background:lightgray; 
} 
tr:nth-child(even) 
{ 
    background:white; 
} 

但就像w3cschools說,它不支持IE8和更早的版本,我不知道是否早期版本的Chrome等其他主流瀏覽器,Firefox和Safari也支持這個選擇器?那麼,是否有一種高度兼容的方式來做到這一點?

回答

2
$("#table tbody tr:even").css({"background":"lightgray"}); 

只改變現有元素,它不添加css規則。如果您希望它適用於新元素,則必須在添加元素後再次執行它。只需將它放入您爲click函數提供的事件處理函數中即可。

+0

好的,非常感謝。 – hiway 2013-03-20 12:14:42

0

修改您的腳本標記,如下所示。

<script type="text/javascript"> 
$(function(){ 
    $("input[type='button']").click(function(){ 
     $("#table tbody").append($("<tr>").append($("<td>").text("new"))); 
     ApplyCss(); 
    }); 

    ApplyCss(); 
}); 

function ApplyCss() { 
      /*double-color effect*/ 
    $("#table tbody tr:even").css({"background":"lightgray"}); 
    $("#table tbody tr:odd").css({"background":"white"}); 
} 
</script> 

ApplyCss()功能適用css一旦你在table追加新tr

相關問題