这是我的代码:
<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等其他主流浏览器的早期版本是否也支持这个选择器?那么,有没有一种高度兼容的方式来做到这一点?
最佳答案
$("#table tbody tr:even").css({"background":"lightgray"});
仅更改现有元素,不添加 css 规则。如果您希望它应用于新元素,则必须在添加元素后再次执行它。只需将它放在您提供给 click
函数的事件处理程序中。
关于css - jQuery 是否支持将 CSS 应用于新创建的元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15523034/