Javascript-无法动态创建选中的复选框

时间:2018-08-01 01:38:12

标签: javascript checkbox

我具有以下功能,可动态创建一堆复选框:

var drawGroups = function(){
  var groups = document.getElementById("groups"); //groups element is a div
  groups.innerHTML = "";

  //groupList is an array containing strings
  for(var i in groupList){
    var groupName = groupList[i];

    var cb = document.createElement('input');
    cb.type = "checkbox";
    cb.checked = true; //this seems to do nothing
    groups.appendChild(cb);

    groups.innerHTML += groupName + "<br/>"
  }
}

我读过的所有内容都表明cb.checked = true应该选中该复选框,但似乎没有任何作用。如何创建处于选中状态的复选框?

2 个答案:

答案 0 :(得分:3)

您需要设置defaultChecked属性:

var groupList = ['foo','bar','baz','biz','boz'];

var drawGroups = function(){
  var groups = document.getElementById("groups"); //groups element is a div
  groups.innerHTML = "";

  //groupList is an array containing strings
  for(var i in groupList){
    var groupName = groupList[i];

    var cb = document.createElement('input');
    cb.type = "checkbox";
    cb.defaultChecked = true;
    groups.appendChild(cb);

    groups.innerHTML += groupName + "<br/>"
  }
}
drawGroups();
<div id="groups"></div>

答案 1 :(得分:0)

您可以使用方法\<([!\<\>]@\>)*\</\1

setAttribute