网络编程
位置:首页>> 网络编程>> JavaScript>> js实现复选框的全选和取消全选效果

js实现复选框的全选和取消全选效果

作者:roucheng  发布时间:2024-05-02 17:40:02 

标签:js,复选框,全选,取消全选

在很多网站都有这样的功能,当点击一个全选按钮之后,所有的复选框都会被选中,再点击之后会取消全选,功能非常的人性化,可以省却很多人力,下面就简单介绍一下JS如何实现此功能,代码实例如下:

以下是代码:


<html>
<head>
<meta charset=" utf-8">
<meta name="author" content="http://hovertree.com/" />
<title>JS实现复选框的全选和取消全选 - 何问起</title><base target="_blank" />
<style type="text/css">
 li {
  list-style-type: none;
  font-size: 12px;
  color: blue;
  width: 300px;
  height: 20px;
  line-height: 20px;
 }
 a {
  width: 200px;
  height: 20px;
  float: left;
 }
 .ck {
  float: left;
  width: 26px;
 }
 .time {
  color: red;
  width: 60px;
  height: 20px;
  float: right;
 }
 .dohovertree {
  font-size: 12px;
 }
</style>
<script type="text/javascript">
window.onload=function()
{
var checkboxs=document.getElementsByName("myHove"+"rTreechk");
var hvtck=document.getElementById("hvtck");
cklen=checkboxs.length;
hvtck.onclick=function()
{
if(this.checked==true)
{
 for(var i=0;i<cklen;i++)
 {
 checkboxs[i].checked=true;
 }
 document.getElementById("dohovert"+"ree").innerHTML="取消"
}
else
{
 for(var i=0;i<cklen;i++)
 {
 checkboxs[i].checked=false;
 }
 document.getElementById("dohovertree").innerHTML="全选"
}
}
}
</script>
</head>
<body>
<h3>JS实现复选框的全选和取消全选 何问起</h3>
<div style="width:736px">
 <a href="http://hovertree.com">首页</a> <a href="http://hovertree.com/texiao/">更多特效</a> <a href="http://hovertree.com/hvtart/bjae/91eqf5ge.htm">原文</a>
</div>
<div>
 <ul>
  <li>
   <span class="ck"><input type="checkbox" name="myHoverTreechk" /></span>
   <a href="http://hovertree.com/">何问起欢迎您</a>
   <span class="time">2014-12-13</span>
  </li>
  <li>
   <span class="ck"><input type="checkbox" name="myHoverTreechk" /></span>
   <a href="http://hovertree.com/hvtart/bjae/91eqf5ge.htm">大家好,好久不见了</a>
   <span class="time">2015-12-03</span>
  </li>
  <li>
   <span class="ck"><input type="checkbox" name="myHoverTreechk" /></span>
   <a href="http://hovertree.com/menu/javascript/">何问起JS</a>
   <span class="time">2015-11-13</span>
  </li>
 </ul>
 <div>
  <input type="checkbox" id="hvtck" />
  <span class="dohovertree" id="dohovertree">全选</span>
 </div>
</div>
</body>
</html>

以上代码实现了复选框的全选与不全选效果,下面就简单介绍一下如何实现此功能。

一、通过下面两个语句分别获取要选取的复选框对象集合和要点击的复选框对象:


var checkboxs=document.getElementsByName("myHove"+"rTreechk");
var hvtck=document.getElementById("hvtck");

通过以下语句获取要选取复选框的数量:

cklen=checkboxs.length;

二、为myck对象绑定onclick事件处理函数。事件处理函数事先判断hvtck对象是否被选中,如果被选中的话,则遍历复选框,挨个取消选中状态,并且通过document.getElementById("dohovertree").innerHTML="取消"将dohovertree元素中的文本设置为取消,else语句中的原理是一样的,这里就不重复介绍了。

来源:http://www.cnblogs.com/roucheng/p/jscheck.html

0
投稿

猜你喜欢

手机版 网络编程 asp之家 www.aspxhome.com