- 首页 > it技术 > >
Js动态生成checkbox(使用Json数据)
-
- 根据Json动态生成checkbox - 锐客网
- body {
- margin: 0 auto;
- }
- #show {
- margin: 10px auto;
- width: 450px;
- font-size: 14px;
- }
- .content {
- float: left;
- width: 450px;
- margin: 10px 0px 20px 10px;
- }
- .bigfont {
- font-size: 14px;
- }
- .la {
- float: left;
- width: 50px;
- height: 20px;
- margin: 5px 0;
- line-height: 20px;
- }
- .la input {
- float: left;
- }
- .la span {
- float: left;
- line-height: 20px;
- }
- window.onload = function () {
- var years = ["2013", "2014"];
- var months = {
- "2013": [12, 11, 10, 9, 8, 7],
- "2014": [6, 5, 4, 3, 2, 1]
- };
- var yearMonth = [years, months];
- genCheck(yearMonth);
- }
- function genCheck(yearMonth) {
- var content = "content";
- var checkText = "checkbox";
- var link = "link";
- var size;
- $("#show").html("");
- var years = yearMonth[0];
- size = years.length;
- for (var i = 0;
i < years.length;
i++) {
- genShowContent("show", checkText + i, i, years[i] + "年", content + i);
- }
- var monthObj = yearMonth[1];
- for (var i = 0;
i < years.length;
i++) {
- var array = monthObj["" + years[i] + ""];
- for (var j = 0;
j < array.length;
j++) {
- genCheckBox(content + i, link + i, array[j], array[j] + "月", i, false);
- }
- var flag = isAllCheck(link + i);
- var box = document.getElementById(checkText + i);
- if (flag) {
- box.checked = true;
- } else {
- box.checked = false;
- }
- $("input[name=" + link + i + "]").each(function () {
- $(this).unbind();
- $(this).change(function () {
- var flag = isAllCheck($(this).attr("name"));
- var box = document.getElementById(checkText + $(this).attr("parentIndex"));
- if (flag) {
- box.checked = true;
- } else {
- box.checked = false;
- }
- });
- });
- }
- for (var i = 0;
i < size;
i++) {
- $("#" + checkText + i).unbind();
- $("#" + checkText + i).change(function () {
- var temp = link + $(this).attr("index");
- var p = document.getElementById(checkText + $(this).attr("index"));
- var box = document.getElementsByName(temp);
- for (var j = 0;
j < box.length;
j++) {
- if (p.checked) {
- box[j].checked = true;
- } else {
- box[j].checked = false;
- }
- }
- });
- }
- }
- function genCheckBox(id, name, value, showText, parentIndex, isCheck) {
- if (!isCheck) {
- var checkbox = "").concat(showText).concat("
");
$("#" + id).append(checkbox);
} else {
var checkbox = "").concat(showText).concat(" ");
$("#" + id).append(checkbox);
}
}
function genShowContent(id, checkboxId, index, showText, idName) {
var showContent = "".concat(showText).concat(": 全选 ");
$("#" + id).append(showContent);
}
function isAllCheck(name) {
var box = document.getElementsByName(name);
for (var j = 0;
j < box.length;
j++) {
if (!box[j].checked) {
return false;
}
}
return true;
}
演示地址:http://zhangjikai.com/demo/html/checkbox.html
推荐阅读