转换无序列表以选择...但有一个扭曲

时间:2015-03-09 12:15:56

标签: javascript jquery html html-lists

我将无序的商品列表转换为选项菜单。

HTML:

<div class="dropdown-container converted">
    <button class="button__black __small" data-dropdown="drop1" aria-controls="drop1" aria-expanded="false">Artist <img src="{site_url}/do-not-enter-or-modify-or-erase/site-theme/img/dropdown-arrow.png" alt="Dropdown" /></button>
    <ul id="drop1" class="f-dropdown mega book-filter-dropdown category-dropdown" data-dropdown-content aria-hidden="true" tabindex="-1">
        <li><a href="#">Item 1</a></li>
        <li class="active"><a class="active" href="#">Item 2</a></li>
        <li><a href="#">Item 3</a></li>
    </ul>
</div>

和Javascript:

// Create the dropdown base
$("<select />").appendTo(".converted");

//Create default option "Go to..."
$("<option />", {
  "selected": "selected",
  "value"   : "catalog/products",
  "text"    : "All Artists"
}).appendTo(".converted select");

// Populate dropdown with menu items
$(".converted a").each(function() {
  var el = $(this);
  $("<option />", {
    "value"   : el.attr("href"),
    "text"    : el.text()
  }).appendTo(".converted select");
});

$(".converted select").change(function() {
  window.location = $(this).find("option:selected").val();
});

我喜欢带有&#34;活跃&#34;类的列表项要在选择下拉列表中显示为&#34; selected = selected&#34;。

我该怎么做?

2 个答案:

答案 0 :(得分:1)

你应该有attr selected=true|false。在el.prop('selected', true|false)中查看$.prop或在创建元素时传递值:

$("<option />", {
    "value"   : el.attr("href"),
    "text"    : el.text(),
    "selected": el.hasClass("active")
}).appendTo(".converted select");

答案 1 :(得分:0)

您可以通过添加active部分中.each()类的检查来实现此目的。另外,我建议从。.appendTo()中删除each()函数,因为追加到DOM是一项非常昂贵的操作,因此您需要做的是在{中创建一个元素数组{1}}然后将该数组一次追加。

考虑这样的事情:

.each()

这可以在网上看到:http://jsfiddle.net/3n34g90q/

相关问题