我正在将无序列表的项目转换为选择的选项菜单。
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();
});
我希望将类别为“active”的列表项作为“selected=selected”的选项显示在选择下拉列表中。
我该怎么做?
最佳答案
您应该具有属性selected=true|false
。要么看看 $.prop如 el.prop('selected', true|false)
或在创建元素时传入值:
$("<option />", {
"value" : el.attr("href"),
"text" : el.text(),
"selected": el.hasClass("active")
}).appendTo(".converted select");
关于javascript - 将无序列表转换为选择...但有一个转折,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28941771/