javascript - 勾选的复选框列出包含其名称的元素

标签 javascript jquery

我想做以下事情:

example

描述

当选中Ingredients selection 下的复选框时,仅应显示使用选中成分的菜肴。使用复选框是因为应该能够一次选择多种成分。

因此,如果 tomatogarlic 被选中,那么只有 spaghetti 这道菜应该在 Dishes 下可见.

代码

my_html.html

<h1>Ingredients selection</h1>   
  <ul class="ingredient">
    <li><label>tomato</label><input type="checkbox" name="" value=""></li>
    <li><label>garlic</label><input type="checkbox" name="" value=""></li>
    <li><label>peas</label><input type="checkbox" name="" value=""></li>
  </ul>

<h1>Dishes</h1>
  <ul class="dish">
    <li style="display:none">spaghetti<span>[Ingredient: tomato, Ingredient: garlic]</span></li>
    <li style="display:none">stir_fry<span>[Ingredient: garlic, Ingredient: peas]</span></li>
    <li style="display:none">ice_cream<span>[Ingredient: sugar, Ingredient: milk]</span></li>
  </ul>

<script 
  src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js">
</script>
<script src="/static/js/script.js"></script>

请注意,这些值是通过模板语言从数据库生成的。

我走了多远:

script.js

$(function () {
  ////Jquery in here/////
  $("input").change(function () {
    if (this.checked) {
      var selected_ingredient = $(this).parent().text();
      var dishes = $("ul.dish").html();
      /*
      // Pseudocode
      for li_element in dishes{
        if (selected_ingredient in li_element){
          li_element.overwrite_attribute(style, "display:block");
        }
      }
      */
    }

  });
});

如何实现此功能?

Here是代码的演示。

最佳答案

像这样:

$(function () {
    $(".ingredient input").on('change', function () {
        var check = $.map($(".ingredient input:checked"), function(el) {
            return $(el).siblings('label').text();
        });

        $('.dish li').hide().each(function(_, self) {
            for (var i=0; i<check.length; i++) {
                if ( $(self).find('span').text().toLowerCase().indexOf( check[i].toLowerCase() ) != -1 ) 
                    $(self).show();
            }    
        });
    });
});

FIDDLE

关于javascript - 勾选的复选框列出包含其名称的元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17763128/

相关文章:

javascript - 预填充文本字段的脚本

jquery - 使用JQuery访问文本框数组id的正确方法

jquery限制字符数

javascript - jQuery onclick 不适用于具有数据切换和数据目标的按钮

javascript - Fonts' Resizer - 如何制作将更改 html 中所有标签字体大小的按钮

jquery - 是否可以使用 jquery 以编程方式模拟 <a href> 标签上的点击?

javascript - Twitter 嵌入(使用 wordpress)并加载?

jquery ajax - 如何处理 json 响应

javascript - 如何从 Kendo Grid 事件将参数数据传递到 mvc 中的 Controller ?

javascript - 将 ParticleJS 与 Gatsby 结合使用