0

我刚开始使用javascript,所以如果我的问题看起来很愚蠢,请原谅我。我想设计一个带有一些复选框的网页,这样当第一个被选中时,其他的就会被启用。我如何使用 JS 做到这一点?我写了以下代码:

function checkBox() {
    if (window.document.form1.mainbox.checked=true) {
        for (i=0;i<window.document.form1.Others.length;i++) {
            window.document.form1.Others[i].disabled=false;
        }
    }
    else {
        for (i=0;i<window.document.form1.Others.length;i++) {
            window.document.form1.Others[i].disabled=true;
        }
    }
}

这个html:

<form name="form1">
<input name="mainbox" value="mainbox" onclick="checkBox()" type="checkbox"> Mainbox<br>
<input disabled="disabled" checked="checked" tabindex="0" name="Others"   type="checkbox">No. 1<br>
<input disabled="disabled" checked="checked" tabindex="1" name="Others" type="checkbox"> No. 2<br>
<input disabled="disabled" checked="checked" tabindex="2" name="Others" type="checkbox"> No. 3<br>
</form>

问题是,在第一次单击时,其他复选框确实被启用,但在随后的单击中没有任何反应,即它们不会再次被禁用。我该如何纠正这个问题?任何帮助将不胜感激。谢谢!

编辑

我遵循了gabitzish的建议,它奏效了。但是,我现在想将 Others 作为参数传递,所以我写:

<input name="mainbox" value="mainbox" onclick="checkBox(Others)" type="checkbox"> Mainbox<br>

并修改脚本如下:

window.checkBox = function(chkname) {
    if (window.document.form1.mainbox.checked==true) {
        for (i=0;i<window.document.form1.chkname.length;i++) {
            window.document.form1.chkname[i].disabled=false;
        }
    }
    else {
        for (i=0;i<window.document.form1.chkname.length;i++) {
            window.document.form1.chkname[i].disabled=true;
        }
    }
}

但这不起作用。请帮帮我。我将非常感激。

4

2 回答 2

2

这条线有问题(你缺少一个=)

if (window.document.form1.mainbox.checked=true)

尝试将其更改为

if (window.document.form1.mainbox.checked)
于 2012-04-13T12:21:30.190 回答
1

我用你的代码创建了一个 jsFiddle,并做了一些小的改动:http: //jsfiddle.net/CUeDg/1/

原始代码的问题是单击时未找到 checkBox() 函数。

编辑: 这是稍后编辑您的问题的解决方案:http: //jsfiddle.net/CUeDg/3/ 我已将参数作为字符串传递给函数。

稍后编辑: 我怀疑您需要该参数来知道您需要切换哪些复选框。我也为此做了一个jsFiddle:http: //jsfiddle.net/CUeDg/5/ (如果我怀疑错了,不要考虑这部分答案)

于 2012-04-13T12:27:03.680 回答