【问题标题】:How to remove duplicate items from an html dropdown using jquery?如何使用 jquery 从 html 下拉列表中删除重复项?
【发布时间】:2013-03-26 20:26:43
【问题描述】:

我查看了一些线程,但使用我的代码我无法完成这项工作。我的 jquery 使用 xml 文件中的信息创建一个 html 下拉列表。我需要删除下拉菜单的重复选项。这不是必需的,但我还需要弄清楚如何仅显示从下拉列表中选择的类别中的项目。

所以现在它显示每个类别的次数与它在 xml 中出现的次数一样多。目标是让它显示每个类别一次。非常感谢您提供有关如何仅显示包含该类别的项目的提示。

jQuery:

$(document).ready(function () {
    $.ajax({
        type: "GET",
        url: "XML/store.xml",
        dataType: "xml",
        success: function (xml) {
            $(xml).find("info").each(function () {
                var option = $(this).find('category').text();

                $('#dropdown').append('<option>' + option + '</option>');



            });
        }
    });
});

HTML:

<form>
<select id="dropdown">
    <option></option>
</select>
</form>

XML 示例:

<products>
<info>
<image>
  <src>images/bosubalancetrainer.jpg</src>
</image>
<name>Bosu Sport Balance Trainer</name>
<brand>Bosu</brand>
<price>$85.95</price>
<category>Bosu Ball</category>
</info>
<info>
<image>
  <src>images/bosupro.jpg</src>
</image>
<name>Bosu Pro Balance Trainer</name>
<brand>Bosu</brand>
<price>$149.95</price>
<category>Bosu Ball</category>
</info>
<info>
<image>
  <src>images/bowflexdumbbell.jpg</src>
</image>
<name>552 Adjustable Dumbbells</name>
<brand>Bowflex</brand>
<price>$349.00</price>
<category>Weights</category>
</info>
<info>
<image>
  <src>images/bowflexbench.jpg</src>
</image>
<name>5.1 Series Bench</name>
<brand>Bowflex</brand>
<price>$259.00</price>
<category>Equipment</category>
</info>
</products>

【问题讨论】:

标签: jquery html xml drop-down-menu


【解决方案1】:

添加检查条件..

success: function (xml) {
      var arr = new Array();
      $(xml).find("info").each(function () {
           var option = $(this).find('category').text();
           if($.inArray(option, arr) > -1) {
               // Do nothing 
           }
           else {
               $('#dropdown').append('<option>' + option + '</option>');
                // Push into array
               arr.push(option);
           }
     });
}

【讨论】:

    【解决方案2】:
    $(document).ready(function(){
       $("select").each(function () {
           var selectedItem = $(this).find('option').filter(':selected').text();
           var selectedItemValue = $(this).find('option').filter(':selected').val();
           $(this).children("option").each(function(x){
               if(this.text == selectedItem && $(this).val() != selectedItemValue) {
                   $(this).remove();
                }
            });
        }); 
    });
    

    打败这个!!!

    【讨论】:

      猜你喜欢
      • 2014-01-21
      • 2012-03-11
      • 2015-12-15
      • 1970-01-01
      • 1970-01-01
      • 2014-05-24
      • 1970-01-01
      • 1970-01-01
      • 2017-01-24
      相关资源
      最近更新 更多