点击当前行就可以选中checkbox复选框

快乐打工仔 分类:实例代码

很多实际应用中,可能有这样的效果,我们想选中复选框的时候,根本不需要直接点击复选框。

点击复选框的所在的行就可以实现,下面就通过代码示例做一下简单介绍。

代码如下:

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="author" content="http://www.pipipi.net/" />
<title>前端教程网</title>
<style type="text/css">
#items{
  width:900px;
  height:auto;
  margin:0 auto;
  padding:5px 0;
  clear:both;
}
#items ul, #items li{
  list-style:none;
}
#items li{
  width:500px;
  height:28px;
  text-align:left;
  padding-left: 0px;
  line-height:28px;
  border-bottom:dashed 1px #CCC;
  cursor:pointer;
}
</style>
<script src="http://libs.baidu.com/jquery/1.9.0/jquery.js"></script>
<script type="text/javascript">
$(document).ready(function(){
  $("#items li").click(function(){
    if($(this).find(":checkbox").prop("checked")){
      $(this).find(":checkbox").prop("checked",false);
    }else{
      $(this).find(":checkbox").prop("checked",true);
    }
    $("#items li input").click(function(ev){
      ev.stopPropagation();
    })
  })
});
</script>
</head>
<body>
<div id="items">
  <ul>
    <li><input type="checkbox"/>前端教程网欢迎您,只有努力奋斗才会有美好的未来</li>
    <li><input type="checkbox"/>没有任何人一开始就是高手,必须要好好学习</li>
    <li><input type="checkbox"/>本站的url地址是pipipi.net</li>
    <li><input type="checkbox"/>每一天都是新的,所以要好好真心当前时间</li>
    <li><input type="checkbox"/>div css教程里面有大量详实的代码</li>
  </ul>
</div>
</body>
</html>

上面的代码实现了我们的要求,下面介绍一下它的实现过程。

一.代码注释:

(1).$(document).ready(function(){}),当文档结构完全加载完毕再去执行函数中的代码。

(2).$("#items li").click(function(){}),为li元素注册click时间处理函数。

(3).if($(this).find(":checkbox").prop("checked")){},判断当前li下的复选框是否被选中。

(4).$(this).find(":checkbox").prop("checked",false),如果被选中,那么就取消选中。

(5).else{

  $(this).find(":checkbox").prop("checked",true);

},如果没有被选中,那么就将其选中。

(6).$("#items li input").click(function(ev){

  ev.stopPropagation();

}),这个很重要,组织点击复选框的冒泡效果,否则点击当前复选框选中或者取消选中之后,事件又会冒泡的li元素,触发注册在li元素上的click事件处理函数,导致无法成功选中或者取消选中。

二.相关阅读:

(1).click事件可以参阅jQuery click事件一章节。

(2).find()方法可以参阅jQuery find()一章节。

(3).prop()可以参阅jQuery prop()一章节。

(4).stopPropagation()可以参阅jQuery event.stopPropagation()一章节。

回复

我来回复
  • 暂无回复内容