jQuery选择器简单应用

来源:互联网 发布:淘宝图片用什么软件 编辑:程序博客网 时间:2024/05/15 23:52

用Js写一些例如全选、反选等功能的时候,会感觉代码相当的多,而如果用jQuery选择器的话就会相当的简洁了

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"><html><head><meta http-equiv="Content-Type" content="text/html; charset=UTF-8"><title>jQueryTest</title><script type="text/javascript" src="jquery-1.9.1.min.js"></script></head><body><table align="center" border="1"><tr><td><input type="checkbox"/></td></tr><tr><td><input type="checkbox"/></td></tr><tr><td><input type="checkbox"/></td></tr><tr><td><input type="checkbox"/></td></tr><tr><td><input type="checkbox"/></td></tr><tr><td><input type="button" value="全选中"/></td><td><input type="button" value="全取消"/></td><td><input type="button" value="反选"/></td></tr></table>    <script type="text/javascript">$(":button:eq(0)").click(function(){$(":checkbox").attr("checked","checked").prop("checked",true);});$(":button:eq(1)").click(function(){$(":checkbox").removeAttr("checked").prop("checked",false);});$(":button:eq(2)").click(function(){var $notChecked=$(":checkbox:not(:checked)");var $checked=$(":checkbox:checked");$notChecked.attr("checked","checked").prop("checked",true);$checked.removeAttr("checked").prop("checked",false);});</script></body></html>

需要注意的是:

$(":button:eq(0)").click(function(){$(":checkbox").attr("checked","checked");});$(":button:eq(1)").click(function(){$(":checkbox").removeAttr("checked");});$(":button:eq(2)").click(function(){var $notChecked=$(":checkbox:not(:checked)");var $checked=$(":checkbox:checked");$notChecked.attr("checked","checked");$checked.removeAttr("checked");});
在IE8经过测试上面这段Js代码可以运行,但在firefox上面运行就有问题,查看了一下官网上面的说明,发现如果是checkbox会比较特殊,需要调用prop()来设置。

1
2
3
4
5
6
7
8
9
// Correct if changing the attribute is desired
$(elem).attr("checked", "checked");
// Correct for checking the checkbox
$(elem).prop("checked", true);
// Correct if removing the attribute is desired
$(elem).removeAttr("checked");
// Correct for clearing the checkbox
$(elem).prop("checked", false);

由于这里不能直接写入js代码,都被屏蔽了,所以只插入了一个没效果的多选表。

另附上jQuery的下载地址右击鼠标另存为就行了

另外可以上jQuery的官网上面去看http://jquery.com/

原创粉丝点击