Heim  >  Artikel  >  Web-Frontend  >  javascript实现checkBox的全选,反选与赋值_javascript技巧

javascript实现checkBox的全选,反选与赋值_javascript技巧

WBOY
WBOYOriginal
2016-05-16 16:10:141075Durchsuche

我们平时在做项目的时候,经常会遇到需要实现实现checkBox的全选,反选与赋值的情况,网上也有许多的范例,这里给大家分享的是本人常用的方法,推荐给大家。

复制代码 代码如下:

//js 数值是否在数组中
Array.prototype.in_array = function(e){
  for(i=0;i     if(this[i] == e)
      return true;
  }
  return false;
}
//js数组index
Array.prototype.find_str=function(string){
  var str = this.join("");
  return str.indexOf(string);
}
var houseIds=new Array();
$("#chebox-list-all").click(function(){
  if($("#chebox-list-all").attr("checked")){
    $("[name='checkboxes']").attr("checked",'true');//全选 增加id
    var ids = document.getElementsByName('checkboxes');
    var value = new Array();
    for(var i = 0; i       if(ids[i].checked)
      houseIds.push(ids[i].value);
    }
  alert(houseIds);
  }else{
    $("[name='checkboxes']").removeAttr("checked");//反选 删除Ids
    houseIds=[];
    alert(houseIds);
  }
})
//单选增加id
function check(obj){
  if(!houseIds.in_array(obj.value)){
    houseIds.push(obj.value);
    alert(houseIds);
  }else{
    var index=houseIds.find_str(obj.value);
    houseIds.splice(index, 1)
    alert(houseIds);
  }
}

以上就是本示例的全部代码了,希望对大家学习使用javascript控制checkbox有所帮助。

Stellungnahme:
Der Inhalt dieses Artikels wird freiwillig von Internetnutzern beigesteuert und das Urheberrecht liegt beim ursprünglichen Autor. Diese Website übernimmt keine entsprechende rechtliche Verantwortung. Wenn Sie Inhalte finden, bei denen der Verdacht eines Plagiats oder einer Rechtsverletzung besteht, wenden Sie sich bitte an admin@php.cn