【问题标题】:How to link a checkbox(:checked) to a class?如何将复选框(:checked)链接到一个类?
【发布时间】:2015-11-01 11:32:52
【问题描述】:

我已经设置了一个过滤器列表,其中包含复选框。选中特定复选框时,我需要与类进行交互,以便通过JavaScript隐藏。此外,如果选中了多个复选框,我需要在两个类中显示这些项目。我有这个:

HTML:

   <div class="categs" id="filters">

                <div class="categhead">
                    <p>Ranking</p>
                </div>
                <div class="categsort">
                    <input class="hide-checkbox" type="checkbox" id="tagchallenger" value="challenger" style="display: none;">
                    <label for="tagchallenger">Challenger</label>
                </div>

                <div class="categsort">
                    <input class="hide-checkbox" type="checkbox" id="tagmaster" value="master" style="display: none;">
                    <label for="tagmaster">Master | Diamond</label>
                </div>
                <div class="categsort">
                    <input class="hide-checkbox" type="checkbox" id="tagplat" value="plat" style="display: none;">
                    <label for="tagplat">Platinum | Gold</label>
                </div>

                <div class="categsort">
                    <input class="hide-checkbox" type="checkbox" id="tagsilver" value="silver" style="display: none;">
                    <label for="tagsilver">Silver | Bronze</label>
                </div>

                <script type="text/javascript">
                [].forEach.call(document.querySelectorAll('.hide-checkbox'), function(element) {
                    element.style.display = 'none';
                });
                </script>

            </div>

JavaScript:

     var streameach = $('.streampic .row .col-md-4');

     function updateContentVisibility(){
     var checked = $('#filters :checkbox:checked');
     if(checked.length){
     streameach.hide();
     checked.each(function() {

        $("." + $(this).val()).show();
     });

     } else {
     streameach.show();
     }
     }

     $('#filters :checkbox').click(updateContentVisibility);
     updateContentVisibility();
     }

然后我也有

     <div class="streamtag1">...</div>

    var stream0 = "<? echo $lolarray->streams[0]->channel->name; ?>";
    if (stream0 == "riotgames") {

    $('streamtag1').addClass('master');

    };

现在,当单击“master”复选框时,它会隐藏所有 div,但不会显示添加了 master 类的那些,它应该连接到该复选框。

【问题讨论】:

  • streameach 未定义,请发布工作代码
  • console.log(checked); - 查看您的代码是否捕获了正确的复选框。
  • 它在您的代码的精简版本中运行良好:jsfiddle.net/zkn7vw6e。所以,问题一定出在其他地方。发布完整的代码或者更好的 jsFiddle 对您很有帮助。
  • “女巫复选框”,哈哈 ...
  • 我认为您必须设置一个带有多个复选框的非工作示例,以向我们展示这应该如何工作?

标签: javascript jquery html checkbox filtering


【解决方案1】:

我会像下面这样设置它:

Here's a jsFiddle

     function updateContentVisibility() {
         $('.hide-checkbox').each(function () {
             if ($(this).is(':checked')) {
                 $('.' + $(this).val()).hide();
             } else $('.' + $(this).val()).show();
         });
     }

     $('.hide-checkbox').change(function () {
         updateContentVisibility();
     });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
  
<div class="categsort">
<input class="hide-checkbox" type="checkbox" id="tagriot" value="riot">
<label for="tagriot">RIOT</label>
<input class="hide-checkbox" type="checkbox" id="tagblue" value="blue">
<label for="tagblue">blue</label>
<input class="hide-checkbox" type="checkbox" id="taggreen" value="green">
<label for="taggreen">green</label>
<input class="hide-checkbox" type="checkbox" id="tagred" value="red">
<label for="tagred">red</label>
</div>
<div class="riot">riot</div>
<br>
<div class="blue">blue</div>
<br>
<div class="green">green</div>
<br>
<div class="red">red</div>
<br>

【讨论】:

    【解决方案2】:

    鉴于问题描述,以及 cmets 对该问题的一些澄清,我建议使用以下方法,使用 jQuery:

    // selecting the <input> elements of class-name 'hide-checkbox',
    // binding an anonymous function to handle the 'change' event:
    $('input.hide-checkbox').on('change', function () {
    
      // selecting all elements whose class-name is equal to the
      // <input> element's value, and using the toggle(switch)
      // approach, to show if the switch is true (the checkbox is checked)
      // and hide if the switch is false (the checkbox is unchecked):
      $('.' + this.value).toggle(this.checked);
    
    // triggering the change event, so that the function runs on page-load,
    // to hide/show as appropriate:
    }).change();
    

    [].forEach.call(document.querySelectorAll('.hide-checkbox'), function(element) {
      element.style.display = 'none';
    });
    
    $('input.hide-checkbox').on('change', function() {
      $('.' + this.value).toggle(this.checked);
    }).change();
    label {
      cursor: pointer;
    }
    input:checked + label {
      color: #f90;
    }
    #contents div[class] {
      border: 1px solid #000;
      border-radius: 1em;
      padding: 0.5em;
      margin: 0 auto 0.5em auto;
      width: 80%;
    }
    #contents div[class]::before {
      content: attr(class);
    }
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <div class="categs" id="filters">
      <div class="categhead">
        <p>Ranking</p>
      </div>
      <div class="categsort">
        <input class="hide-checkbox" type="checkbox" id="tagchallenger" value="challenger" style="display: none;" />
        <label for="tagchallenger">Challenger</label>
      </div>
      <div class="categsort">
        <input class="hide-checkbox" type="checkbox" id="tagmaster" value="master" style="display: none;" />
        <label for="tagmaster">Master | Diamond</label>
      </div>
      <div class="categsort">
        <input class="hide-checkbox" type="checkbox" id="tagplat" value="plat" style="display: none;" />
        <label for="tagplat">Platinum | Gold</label>
      </div>
      <div class="categsort">
        <input class="hide-checkbox" type="checkbox" id="tagsilver" value="silver" style="display: none;" />
        <label for="tagsilver">Silver | Bronze</label>
      </div>
    </div>
    
    <div id="contents">
      <div class="challenger"></div>
      <div class="master"></div>
      <div class="plat"></div>
      <div class="silver"></div>
    </div>

    外部JS Fiddle demo,用于实验。

    或者,使用纯 JavaScript:

    // creating a named function to handle the show/hide functionality:
    function toggleView() {
    
        // a cached reference to the changed <input>:
        var control = this,
    
        // a reference to whether the <input> is checked or not:
            check = control.checked,
    
        // retrieving all elements with a class-name equal to the
        // <input> element's value:
            targets = document.querySelectorAll('.' + control.value);
    
        // using Array.prototype.forEach(), with Function.prototype.call(),
        // to iterate over the found elements:
        Array.prototype.forEach.call(targets, function (node) {
    
            // setting the display property of each found-element's
            // style property; if the checkbox is checked we set
            // the display to 'block', if not we set it to 'none':
            node.style.display = check ? 'block' : 'none';
        });
    }
    
    // creating a 'change' event so that we can trigger the function
    // to run on page-load:
    var changeEvent = new Event('change');
    
    // As above, iterating over the '.hide-checkbox' elements:
    Array.prototype.forEach.call(document.querySelectorAll('.hide-checkbox'), function (element) {
    
        // hiding the elements:
        element.style.display = 'none';
    
        // binding the named function (toggleView)
        // to handle the change event:
        element.addEventListener('change', toggleView);
    
        // triggering the change event on each of the
        // '.hide-checkbox' elements:
        element.dispatchEvent(changeEvent);
    });
    

    function toggleView() {
        var control = this,
            check = control.checked,
            targets = document.querySelectorAll('.' + control.value);
        Array.prototype.forEach.call(targets, function (node) {
            node.style.display = check ? 'block' : 'none';
        });
    }
    
    var changeEvent = new Event('change');
    
    Array.prototype.forEach.call(document.querySelectorAll('.hide-checkbox'), function (element) {
        element.style.display = 'none';
        element.addEventListener('change', toggleView);
        element.dispatchEvent(changeEvent);
    });
    label {
      cursor: pointer;
    }
    input:checked + label {
        color: #f90;
    }
    #contents div[class] {
        border: 1px solid #000;
        border-radius: 1em;
        padding: 0.5em;
        margin: 0 auto 0.5em auto;
        width: 80%;
    }
    #contents div[class]::before {
        content: attr(class);
    }
    <div class="categs" id="filters">
        <div class="categhead">
            <p>Ranking</p>
        </div>
        <div class="categsort">
            <input class="hide-checkbox" type="checkbox" id="tagchallenger" value="challenger" style="display: none;" />
            <label for="tagchallenger">Challenger</label>
        </div>
        <div class="categsort">
            <input class="hide-checkbox" type="checkbox" id="tagmaster" value="master" style="display: none;" />
            <label for="tagmaster">Master | Diamond</label>
        </div>
        <div class="categsort">
            <input class="hide-checkbox" type="checkbox" id="tagplat" value="plat" style="display: none;" />
            <label for="tagplat">Platinum | Gold</label>
        </div>
        <div class="categsort">
            <input class="hide-checkbox" type="checkbox" id="tagsilver" value="silver" style="display: none;" />
            <label for="tagsilver">Silver | Bronze</label>
        </div>
    </div>
    <div id="contents">
        <div class="challenger"></div>
        <div class="master"></div>
        <div class="plat"></div>
        <div class="silver"></div>
    </div>

    外部JS Fiddle demmo 用于实验/开发。

    参考资料:

    【讨论】:

    • 伙计.. 不知道我在这里做错了什么。我使用 jquery 复制了第一个 javascript 并将其粘贴在下面,甚至使用了您的 css ...单击它时仍然显示所有类,而不是仅单击一个...
    • 链接的演示可以正常工作吗?是否正确调用了 jQuery 或纯 JavaScript 函数(将 console.log("function's called!") 弹出到匿名函数 (jQuery) 和 toggleView() 函数(纯 JavaScript)中作为简单的诊断。您是否将代码包装在 @987654351 @ (或适当的替代方法),或者您的 JavaScript/jQuery 是否在关闭 &lt;/body&gt; 标记之前的 &lt;script&gt; 块中,因此 DOM 在 JavaScript 运行之前就存在?
    • 就我的代码而言,假设我没有为价值挑战者开设课程,但我为大师开设了课程。当我检查挑战者复选框时,它会隐藏所有。当我选中主复选框时,它会隐藏所有,然后再次显示所有。怎么样?
    • 所有 JS 代码都包含在一个
    • 您希望它这样做,还是您对我的回答有疑问?如果这是您想要的,则更新您的问题,显示您尝试显示和隐藏的 HTML 的代表性示例,并清楚地更新问题文本以更好地解释您想要的内容(正如您在该评论中所做的那样,尽管我我不确定这是请求还是批评)。我建议,如果您使用的是 jQuery,请尝试使用 $(document).ready(); 进行包装,以查看它是否有效。否则,您的控制台中是否有任何错误?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-09-29
    • 1970-01-01
    • 2013-08-11
    • 2011-02-09
    相关资源
    最近更新 更多