【问题标题】:filtering data based on a custom data attribute using jquery使用 jquery 基于自定义数据属性过滤数据
【发布时间】:2012-02-16 23:47:46
【问题描述】:

我想知道是否有人可以提供一些 jquery 代码来执行以下操作。 我有一个下拉选择列表输入,我想过滤复选框列表。

这是我的 html 代码的样子

 <span style="float:right;">

        <label>Filter</label> 
    <select id="office-type-list" name="OfficeTypes"><option value="00">All</option>

        <option value="05">Township</option>

        <option value="10">Municipality</option>

        <option value="15">Elementary School</option>

        <option value="20">High School</option>

    </select> 

</span>

<!-- List below -->

<div name="Offices">
    <div data-custom-type="00">
        <input type="checkbox" name="Offices" id="Offices_0000" value="0000" /> <label for="Offices_0000">All</label>
    </div>
    <div data-custom-type="05">
        <input type="checkbox" name="Offices" id="Offices_0010" value="0010" /> <label for="Offices_0010">Township 1p</label>
    </div>
    <div data-custom-type="05">
        <input type="checkbox" name="Offices" id="Offices_0020" value="0020" /> <label for="Offices_0020">Township 2</label>
    </div>
</div>

因此,如果选择 Township (05),则只会显示 data-custom-type="05" 的 div。

有没有办法实现这一点,如果有,我们将不胜感激

【问题讨论】:

  • 首先data-custom-type 应该是data-r,除非您只使用HTML5。它可能会在旧浏览器上失败。第二件事,一个div不能有名字,名字只用于输入,把名字改成id。
  • 您选择的答案无法选择一个项目,然后选择“全部”。执行此操作时,仅显示“全部”,而不是所有原始 div/复选框。我的回答也处理这种情况。
  • 你是绝对正确的。我已经继续并更新了我接受的答案。谢谢。
  • 实际上我对细节有点模糊,因为我在办公室列表中包含了所有选项。我的坏

标签: jquery filtering custom-data-attribute


【解决方案1】:

试试这个

$("#office-type-list").change(function(){
     $("div[data-custom-type]").hide();
     $("div[data-custom-type=" + this.value +"]").show();
});

【讨论】:

    【解决方案2】:

    你可以这样做:

    $("#office-type-list").change(function() {
        var customType = $(this).val();
        $("div[name=Offices]").children("div").hide().filter(function() {
            return $(this).data("custom-type") == customType;
        }).show();
    });
    

    上面的代码通过匹配作为主Offices元素的直接子元素的&lt;div&gt;元素来处理&lt;select&gt;元素的change事件,将它们全部隐藏,然后应用filter()来获取子元素其data-custom-type 属性与所选值匹配,并显示这些。

    【讨论】:

      【解决方案3】:

      这里有一个 jsFiddle 来测试。

      $('#office-type-list').change(function(){
          var sel = $(this).val();
          $('div[name="Offices"] div').hide();
          if(sel != "00"){
             $('div[data-custom-type="'+sel+'"]').show();
          }
          else {
              $('div[name="Offices"] div').show();
          }
      });
      

      如果选择“全部”,则显示所有选项,否则仅显示匹配的元素。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-07-01
        • 2021-09-23
        相关资源
        最近更新 更多