zig*_*ggy 0 html javascript arrays
在以下示例中:
<html>
<head>
<SCRIPT language="JavaScript">
function checkcheckboxElem(checkboxElem)
{
alert ("checkboxElem " + checkboxElem.length);
}
</script>
</head>
<body>
<form name="checkForm">
Master: <input type="checkbox" name="master" value="6694" onclick="checkcheckboxElem(document.checkForm.checkboxElem)"><br>
Child1: <input type="checkbox" name="checkboxElem" value="2">
</form>
</body>
Run Code Online (Sandbox Code Playgroud)
警报输出'undefined'.出于某种原因,如果只有一个复选框,则会执行此操作.如果我添加另一个复选框,则输出正确的长度.如果我按如下所示进行更改,则输出2
<html>
<head>
<SCRIPT language="JavaScript">
function checkcheckboxElem(checkboxElem)
{
alert ("checkboxElem " + checkboxElem.length);
}
</script>
</head>
<body>
<form name="checkForm">
Master: <input type="checkbox" name="master" value="6694" onclick="checkcheckboxElem(document.checkForm.checkboxElem)"><br>
Child1: <input type="checkbox" name="checkboxElem" value="2">
Child2: <input type="checkbox" name="checkboxElem" value="1">
</form>
Run Code Online (Sandbox Code Playgroud)
如果只有一个复选框,为什么它会返回'undefined'?
谢谢
在第一种情况下document.checkForm.checkboxElem是指单个输入元素,在第二种情况下它是指输入元素的数组.你可以这样做:
function checkcheckboxElem(checkboxElem) {
if(!checkboxElem.length)
checkboxElem = [checkboxElem];
alert ("checkboxElem " + checkboxElem.length);
}
Run Code Online (Sandbox Code Playgroud)