假设我从DB中选择数据,结果如下:
var dbObj = ["Z","E"];
然后我要打印3 CheckBox
,即“Z”,“N”,“E”
由于来自DB的数据为[“Z”,“E”],复选框Z 和复选框E 将选中而复选框N 左侧为未选中。结果是这样的:
这是我的源代码,你可以复制它并玩游戏:
<!DOCTYPE html>
<html>
<head>
<title>CheckBox</title>
</head>
<script type="text/javascript">
var dbObj = [];
function validate(selection)
{
switch(selection)
{
case 0:
dbObj = ["Z",1,"E"];
printZNECheckBox();
break;
case 1:
dbObj = ["Z",1,2];
printZNECheckBox();
break;
case 2:
dbObj = ["Z","N","E"];
printZNECheckBox();
break;
case 3:
dbObj = [0, 1, "E"];
printZNECheckBox();
break;
}
}
function printZNECheckBox()
{
for (var i = 0; i < dbObj.length; i++)
{
if (typeof dbObj[i] == 'number')
{
printUnCheckedBox(dbObj[i]);
}
else {printCheckedBox(dbObj[i]);}
}
}
function printCheckedBox(x)
{
document.write("<input type =\"checkbox\" name=\"box\" id=\""+x+ "\" value=\""+x+"\" checked/>"+x);
}
function printUnCheckedBox(x)
{
var str = "";
switch (x)
{
case 0:
str = "Z";
break;
case 1:
str = "N";
break;
case 2:
str = "E";
break;
}
document.write("<input type =\"checkbox\" name=\"box\" id=\""+str+ "\" value=\""+str+"\"/>"+str);
}
</script>
<body>
<input type="button" value="Data 1 from DB" onClick="validate(0)">
<input type="button" value="Data 2 from DB" onClick="validate(1)">
<input type="button" value="Data 3 from DB" onClick="validate(2)">
<input type="button" value="Data 4 from DB" onClick="validate(3)">
</body>
</html>
回到我的问题:
还有更直接的方法来实现JavaScript或Java中的相同目标吗?
答案 0 :(得分:1)
我认为这就是你要找的东西:
<!DOCTYPE html>
<html>
<head>
<title>CheckBox</title>
</head>
<script type="text/javascript">
var dbObj = ["Z","N","E"];
var result = [];
function validate(selection)
{
switch(selection)
{
case 0:
result = ["Z","E"];
printZNECheckBox();
break;
case 1:
result = ["Z"];
printZNECheckBox();
break;
case 2:
result = ["Z","N","E"];
printZNECheckBox();
break;
case 3:
result = ["E"];
printZNECheckBox();
break;
}
}
function printZNECheckBox()
{
for (var i = 0; i < dbObj.length; i++)
{
printCheckedBox(dbObj[i]);
}
}
function printCheckedBox(x)
{
var isChecked = '';
if(result.indexOf(x) != -1 ){ isChecked = "checked"; }
document.write("<input type =\"checkbox\" name=\"box\" id=\""+x+ "\" value=\""+x+"\" "+isChecked+"/>"+x);
}
</script>
<body>
<input type="button" value="Data 1 from DB" onClick="validate(0)">
<input type="button" value="Data 2 from DB" onClick="validate(1)">
<input type="button" value="Data 3 from DB" onClick="validate(2)">
<input type="button" value="Data 4 from DB" onClick="validate(3)">
</body>
</html>