【问题标题】:Efficient way to enabled or disabled multiple checkboxes with JavaScript than listing all of them?与列出所有复选框相比,使用 JavaScript 启用或禁用多个复选框的有效方法?
【发布时间】:2020-12-29 15:14:45
【问题描述】:

我想知道是否有更好的方法来同时启用/禁用多个复选框。 在 html 中,我有两个单选按钮可以在所有头发选项和自定义头发选项之间进行选择,默认所有选项都禁用复选框,而自定义选项则启用它们。
到目前为止,这就是我所得到的工作(可能看起来很愚蠢,我很抱歉),但我想知道是否有更有效的方法来解决这个问题?为了我自己,我希望它尽可能“小”,同时仍然易于阅读/理解。

function checkHaOp(){
    if (document.getElementById("hairOptionAll").checked){
        document.getElementById("hairAuburn").disabled = true;
        document.getElementById("hairBlack").disabled = true;
        document.getElementById("hairBlonde").disabled = true;
        document.getElementById("hairBrown").disabled = true;
        document.getElementById("hairRed").disabled = true;
        document.getElementById("hairOther").disabled = true;
    } 
    else if (document.getElementById("hairOptionCustom").checked){
        document.getElementById("hairAuburn").disabled = false;
        document.getElementById("hairBlack").disabled = false;
        document.getElementById("hairBlonde").disabled = false;
        document.getElementById("hairBrown").disabled = false;
        document.getElementById("hairRed").disabled = false;
        document.getElementById("hairOther").disabled = false;
    }
}

最好使用 javascript,因为我不知道 jquery。
由于我仍在学习,因此我也很感激对事物的解释。

【问题讨论】:

  • 添加一个class=".." 然后做getElementsByClassName("..").forEach(...)
  • @NiettheDarkAbsol HTMLCollections 没有 forEach,您需要 qSA 或 for 代替
  • @CertainPerformance 哎呀,完全正确。 querySelectorAll(".class_name_here").forEach(...)
  • @AlwaysHelping 我无法让它工作,但这可能是我的错/我很笨而且有点匆忙。仅仅因为解释,我才认真考虑选择你的,他们非常好,乐于助人,我真的很感激他们。在我完成项目的 v1 后,我会修改这段特定的代码,如果/当我能弄清楚如何让你的工作正常工作时,我会将最佳答案改为你的,我确实更喜欢它,但另一个第一次尝试,所以我现在选择它。
  • @AlwaysHelping 是的,我看到了,在 sn-p 中也为我工作过,所以我把事情搞砸了。哦,天哪,好吧 okie dokie,如果那是你想做的。我想最好还是离开,以防其他人遇到与我类似的问题并想要选择/解释。

标签: javascript


【解决方案1】:

您可以像@NiettheDarkAbsol 所说的那样添加/使用类 然后是类似的东西。

var inpck = document.getElementsByClassName("input-checkbox");
if (document.getElementById("hairOptionAll").checked) {
    for(var i = 0; i < inpck.length; i++) {
       inpck[i].disabled = true;
    }
}
if (document.getElementById("hairOptionCustom").checked) {
    for(var i = 0; i < inpck.length; i++) {
       inpck[i].disabled = false;
    }
}

现在轮到你重构这个了:D

【讨论】:

  • 只需要一个循环:let isChecked = document.getElementById("hairOptionCustom").checked; 然后遍历集合:inpck[i].disabled = isChecked。 :-)
【解决方案2】:

你可以使用

document.querySelectorAll('[id^=hair]') 

它选择所有id以“头发”开头的元素

<!DOCTYPE html>

<html>
    <body>
        <input type="checkbox" id="hairOptionAll">
        <input type="checkbox" id="hairAuburn">
        <input type="checkbox" id="hairBlack">
        <input type="checkbox" id="hairBlonde">
        <input type="checkbox" id="hairBrown">
        <input type="checkbox" id="hairRed">
        <input type="checkbox" id="hairOther">
    </body>

    <script>
        const hairCb = document.querySelectorAll('[id^=hair]');
        for (let i=0; i<hairCb.length; i++) {
            hairCb[i].disabled = true;
        }
    </script>
</html>

【讨论】:

    【解决方案3】:

    这是优化的解决方案。

    <div class="radio-btns">
        All <input type="radio" id="hairOptionAll" name="hairOptionAll"/>
        Custom <input type="radio" id="hairOptionCustom" name="hairOptionCustom"/>
    </div>
    <div class="hairOptions">
        hairAuburn <input type="checkbox" id="hairAuburn" />
        hairBlack <input type="checkbox" id="hairBlack" />
        hairBlonde <input type="checkbox" id="hairBlonde" />
        hairBrown <input type="checkbox" id="hairBrown" />
        hairRed <input type="checkbox" id="hairRed" />
        hairOther <input type="checkbox" id="hairOther" />
    </div>
    
    
    <script type="text/javascript">
            const radioBtns = document.querySelector('.radio-btns');
            radioBtns.children[0].checked = true;
    
            radioBtns.addEventListener("click", (event) => {
                radioBtns.children[0].checked = (event.target.id == 'hairOptionAll') ? true : false;
                radioBtns.children[1].checked = (event.target.id == 'hairOptionCustom') ? true : false;
    
            const allOptions = [...event.target.parentElement.nextElementSibling.children];
            allOptions.map(option => ( option.checked = (event.target.id == 'hairOptionCustom') ? true : false ) );
            });
    </script>

    【讨论】:

      【解决方案4】:

      这是一个完整的工作代码。为了最小化我们写给我们的code,我们需要使用class选择器而不是id - 给你的单选按钮提供相同的class,然后使用forEach循环遍历所有的收音机@987654328 @。将该类也添加到您的复选框中。

      要获取所有复选框,我们可以使用forEach 方法。

      一旦您拥有所有单选按钮,您需要在特定的radio 按钮上侦听change,然后我们将检查我们选择的radio 按钮是否已选中,其id 是否为@987654333 @ 或custom

      要获得实际点击的radio 按钮的id,我们可以使用getAttribute 方法返回选中的单选按钮的ID。

      如果我们的条件匹配,我们将禁用所有checkboxes,否则我们将使用复选框类上的forEach 循环启用所有checkboxes

      我们将传递truefalse 作为参数来禁用checkboxes 函数以避免有两个loops

      实时工作示例(我还为每一行代码添加了注释/注释以供您理解)

      //Enable disable checkbox
      function disableChekbox(isChecked) {
        let getHairOptions = document.querySelectorAll('.hairOptions') //get all checkboxes
        getHairOptions.forEach(function(x) {
          x.disabled = isChecked
        })
      }
      
      let getHairRadio = document.querySelectorAll('.hairOptionAll') //get all radio buttons
      
      //For each all radio buttons
      getHairRadio.forEach(function(radio) {
        //listen to change on radio
        radio.addEventListener('change', function(e) {
          if (e.target.checked && e.target.getAttribute('id') == 'hairOptionAll') {
            //loop through all checkboxes
            disableChekbox(true)
          } else if (e.target.checked && e.target.getAttribute('id') == 'hairOptionCustom') {
            //loop through all checkboxes
            disableChekbox(false)
          }
        })
      })
      All <input type="radio" id="hairOptionAll" name="hairOptionAll" class="hairOptionAll" />
      
      Custom <input type="radio" id="hairOptionCustom" name="hairOptionAll" class="hairOptionAll" />
      <br>
      <br>
      hairAuburn <input type="checkbox" id="hairAuburn" class="hairOptions" />
      hairBlack <input type="checkbox" id="hairBlack" class="hairOptions" />
      hairBlonde <input type="checkbox" id="hairBlonde" class="hairOptions" />
      hairBrown <input type="checkbox" id="hairBrown" class="hairOptions" />
      
      hairRed <input type="checkbox" id="hairRed" class="hairOptions" />
      hairOther <input type="checkbox" id="hairOther" class="hairOptions" />

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2020-11-14
        • 2017-11-12
        • 2015-05-09
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-10-15
        • 1970-01-01
        相关资源
        最近更新 更多