Pra*_*ant 3 jquery select html-table
我在我的应用程序中创建了一个表,我想在单击复选框时选择(更改背景颜色)整行,与gmail一样,当我们单击gmail中的复选框时,整行变为黄色.
<table>
<tbody>
<tr>
<td><input type="checkbox" name="chk" id="chk" /></td>
<td>My Name</td>
<td>Description of the job</td>
</tr>
</tbody>
</table>
Run Code Online (Sandbox Code Playgroud)
请告诉我如何在jquery中做同样的事情?
$(function() {
$("#chk").click(function() {
$(this).parents("tr").toggleClass("diffColor");
});
});
Run Code Online (Sandbox Code Playgroud)
创建一个CSS类(上面称为"diffColor")并添加背景颜色,如:
<style type="text/css">
tr.diffColor td { background-color: yellow; }
</style>
Run Code Online (Sandbox Code Playgroud)
不要直接设置CSS属性.尽可能使用课程.
Cletus的答案是正确的,但我认为可以稍微改进一下:
$(function() {
$("#chk").click(function() {
$(this)
.parents("tr:first")
.toggleClass("diffColor", this.checked)
;
});
});
Run Code Online (Sandbox Code Playgroud)
这里唯一真正的区别是:
<tr>....你永远不会知道你的代码可能会在哪里结束,而且理论上它会更快一些.此外,您可以考虑将该函数绑定到change处理程序:
$('#chk').bind('click change', function() { // ... etc
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
9879 次 |
| 最近记录: |