继续编写“圳品”信息系统,又增加了两组checkbox,同样需要提供全选、全部取消、反选按钮,并编写相应的代码,其实代码中除了checkbox的tagName之外,都是相同的。
那么我们是否可以将checkbox的tagName作为checkbox全选、全部取消、反选函数的参数传入,从而实现通用的checkbox全选、全部取消、反选函数呢?
答案是可以的,这需要借助eval()。
eval() 函数计算或执行参数。如果参数是表达式,则 eval() 计算表达式。如果参数是一个或多个 JavaScript 语句,则 eval() 执行这些语句。
具体示例代码如下:
<!DOCTYPE html>
<html>
<body>
<div id="divArea">
县(区):
<script>
function showCbStateBox(n)
{
document.write(' <input type="button" value="全选" onclick="checkAll(', "'", n, "'",')" />');
document.write(' <input type="button" value="全部取消" onclick="uncheckAll(', "'", n, "'", ')" />');
document.write(' <input type="button" value="反选" onclick="reverseCheck(', "'", n, "'", ')" />');
}
aArea = new Array(
"河池", //0
"金城江", //1
"宜州", //2
"罗城", //3
"环江", //4
"南丹", //5
"天峨", //6
"东兰", //7
"巴马", //8
"凤山", //9
"都安", //10
"大化"); //11
function showAreaChkBox()
{
var i;
for (i = 0; i < aArea.length; i++)
{
document.write('<input type="checkbox" checked="true" name="',i,'" >',aArea[i],'</input> ');
}
}
showAreaChkBox();
showCbStateBox("cbArea");
</script>
</div>
<div id="divCertYear">
认证时间:
<script>
function showCertYearChkBox()
{
var i, d = new Date();
d = d.getFullYear();
for (i = 2020; i <= d; i++)
{
document.write('<input type="checkbox" checked="true" name="', i, '" >', i, '</input> ');
}
}
showCertYearChkBox();
showCbStateBox("cbCertYear");
</script>
</div>
<div id="divCol">
显示信息包含:
<script>
var g_aCol = new Array("序号","所属县区","企业名称","产品名称","证书编号","认证时间","有效期","备注");
function showColChkBox()
{
var i;
for (i = 0; i < g_aCol.length; i++)
{
document.write('<input type="checkbox" checked="true" name="',i,'" >',g_aCol[i],'</input> ');
}
}
showColChkBox();
showCbStateBox("cbCol");
</script>
</div>
<script>
var divArea = document.getElementById("divArea");
var cbArea = divArea.getElementsByTagName("input");
var divCol = document.getElementById("divCol");
var cbCol = divCol.getElementsByTagName("input");
var divCertYear = document.getElementById("divCertYear");
var cbCertYear = divCertYear.getElementsByTagName("input");
//全选
function checkAll(s)
{
for (i=0; i < 11; i++)
{
eval(s)[i].checked = true;
}
}
//全部取消
function uncheckAll(s)
{
for (i=0; i < 11; i++)
{
eval(s)[i].checked = false;
}
}
//反选
function reverseCheck(s)
{
for (i=0; i < 11; i++)
{
eval(s)[i].checked = !(eval(s)[i].checked);
}
}
</script>
</body>
</html>