2013-03-26 37 views
0

我查看了一些主題,但使用我的代碼無法完成此項工作。我的jquery使用xml文件中的信息創建一個html下拉菜單。我需要刪除下拉菜單中的重複選項。這不是必需的,但我還需要弄清楚如何顯示從下拉列表中選擇的類別中的項目。如何使用jquery從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> 
+1

您是否看到此解決方案? http://stackoverflow.com/questions/1875607/filter-duplicate-options-from-select-dropdown – herrjeh42 2013-03-26 20:33:39

+0

我試圖實現,它失敗了。我是jQuery全新的,所以這可能是爲什麼:/ – swerley 2013-03-26 22:48:24

回答

0

添加檢查條件..

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); 
      } 
    }); 
} 
+0

這就像一個魅力!謝謝! – swerley 2013-03-26 20:36:40

0
$(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(); 
      } 
     }); 
    }); 
}); 

打敗這個!!!

+1

謝謝pranav ...我不知道編輯如此... – Saleh 2014-02-19 12:22:09

相關問題