【问题标题】:Js: Function that Hides Divs According to an array?js:根据数组隐藏div的函数?
【发布时间】:2021-12-16 09:05:35
【问题描述】:

我有 div('items'),每个里面都有复选框。如何隐藏没有选中选中值的复选框的项目?

<div class='item'> <input type='checkbox' value='green' checked></input> <input type='checkbox' value='red'></input> </div>
<div class='item'> <input type='checkbox' value='yellow'></input> <input type='checkbox' value='orange'></input> </div>


function MyFunction () {

const values = ['green', 'red'];
let items = document.querySelectorAll('.item');
items.forEach(items => {
    if (values.every(values => 

        items.querySelectorAll('input[type="checkbox"]:checked')[0].value.includes(values) // working (only for the first checked checkbox)

        items.querySelectorAll('input[type="checkbox"]:checked').forEach((cb, i) => // not working
              cb[i].value.includes(values)
        )
        
    ))
    {
        items.style.display = 'block'
    }
    else {
        items.style.display = 'none'
    }
})

}

在上面的示例中,在触发 myFunction() 后,只应显示第一项,因为它的值是来自 values 的绿色值,并且已被选中。

谢谢!

【问题讨论】:

  • 如果隐藏未选中的复选框,您将如何再次检查它们?
  • 如果容器 (div) 的复选框没有选中指定值(绿色或红色),我想隐藏它。
  • 也许只是不将它们添加到页面中?如果您无法检查它们,则似乎不值得将它们添加到 DOM。
  • 另外,您的 HTML 似乎已关闭。每种颜色都应该在它自己的 div 中,对吗?但是你有一个 div class="item" 和两个复选框。因此,如果仅选中一个颜色复选框,您想隐藏父 div 似乎很奇怪。

标签: javascript arrays if-statement input checkbox


【解决方案1】:
<html>
<body>
    <div class='item'>
        <input type='checkbox' value='green' checked>Green</input>
        <input type='checkbox' value='red'>Red</input>
    </div>
    <div class='item'>
        <input type='checkbox' value='yellow'>Yellow</input>
        <input type='checkbox' value='orange'>Orange</input>
    </div>

<script>
    function MyFunction () {
        const values = ['green', 'red'];
        let items = document.querySelectorAll('.item');
        items.forEach(item => {
            if([].slice.call(item.children).filter(a => a.checked).length > 0) {
                item.style.display = 'block';
            } else {
                item.style.display = 'none';
            }
        });
    }
    MyFunction();
</script>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-02-27
    • 1970-01-01
    • 2014-10-05
    • 1970-01-01
    • 1970-01-01
    • 2014-08-30
    相关资源
    最近更新 更多