0

我有几页长代码,但我很难让它工作。以下脚本在一个主复选框上使用 onclick 命令检查并禁用具有特定 ID 的所有复选框。当用户取消单击该框时,复选标记消失,但仍处于禁用状态。即使他们按下重置按钮,禁用的框也会保留。

Javascript:

 <script>
 function checkAllbase(bx) {
  var cbs = document.getElementsByTagName('input');
  for(var i=0; i < cbs.length; i++) {
    if(cbs[i].id == '1') {
      cbs[i].checked = bx.checked;
      cbs[i].disabled=true;
    }
  }
}
 </script> 
4

2 回答 2

0

元素仍然存在disabled,因为设置的值是一个常量(字面量)true

你可以做的是bx.disabled整个复制,就像你正在做的那样bx.checked

cbs[i].checked = bx.checked;
cbs[i].disabled = bx.disabled;

或者添加另一个参数来传递所需的disabled状态:

function checkAllbase(bx, disabled) {
  disabled = disabled !== false; // limit to `true` or `false`, prefer `true`
  // ...
    cbs[i].checked = bx.checked;
    cbs[i].disabled = disabled;
  // ...
}

// usage
checkAllbase(bx);        // disables elements
checkAllbase(bx, true);  // also disables elements
checkAllbase(bx, false); // enabled elements
于 2013-07-31T09:24:30.143 回答
0

为与包关联的每个复选框输入提供相似的名称或类。在没有看到您的实际 html 的情况下,在下面提供示例 html

HTML

<input type="checkbox" class="package1" name="package1[]" value="vacation">
<input type="checkbox" class="package1" name="package1[]" value="bonus">
<input type="checkbox" class="package1" name="package1[]" value="fries">

JS

function togglePackage(isChecked,packageName) {
  //Choose one of the two below to use

  //Below selects the inputs by the class name
  var cbs = document.querySelectorAll("input."+packageName);
  //Or Below selects the inputs by the input name
  var cbs = document.querySelectorAll("input[name^="+packageName+"]");

  for(var i=0; i<cbs.length; i++) {
        //Since they are either checked and disabled (both true)
        //or unchecked and enabled (both false) we can just use
        //isChecked to set both at once.
        cbs.checked = isChecked;
        cbs.disabled = isChecked;
  }
}

//Then somewhere call the togglePackage function
//bx here would be the main checkbox that you want to 
//have toggling the other boxes, and "package1" is obviously
//the name or the class you gave the checkboxes.
togglePackage(bx.checked,"package1");
于 2013-07-31T09:49:26.143 回答