使用jQuery根据无序列表选择选择选项 [英] Make select option selected based on an unordered list using jQuery
本文介绍了使用jQuery根据无序列表选择选择选项的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我已经将无序列表转换为选择选项列表,但是我不确定如何使'selected'属性添加与列表中相同超链接相关的选项.
I've converted my unordered list into a select option list, however I'm not sure how can I make the 'selected' attribute added the option which correlates to the same hyperlink in the list.
标记
<div class="navigation">
<ul>
<li><a href="foo.html">Foo</a></li>
<li><a href="bar.html" class="selected">Bar</a></li>
<li><a href="boo.html">Boo</a></li>
</ul>
</div>
JavaScript
Javascript
$('<select />').appendTo('.navigation');
// Populate dropdown with menu items
$('.navigation ul a').each(function() {
var el = $(this);
$('<option />', {
"value" : el.attr('href'),
"text" : el.text()
}).appendTo('.navigation select');
});
// Navigate to page on select option
$('.navigation select').change(function() {
window.location = $(this).find('option:selected').val();
});
// Hide navigation list
$('.navigation ul').hide();
推荐答案
您可以使用 hasClass
方法:
$('<option />', {
"value" : el.attr('href'),
"text" : el.text(),
"selected" : el.hasClass('selected')
}).appendTo('.navigation select');
这篇关于使用jQuery根据无序列表选择选择选项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文