Make select option selected based on an unordered list using jQuery

陌路散爱 提交于 2021-02-18 23:42:03

问题


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.

Mark-up

<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

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

回答1:


You can use hasClass method:

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

http://jsfiddle.net/5V5rY/




回答2:


You seem to dynamically create the select element .

So you need to delegate the event to the closest static parent container to let it work..

$('.navigation select').change(function() {

supposed to be

$('.navigation').on('change', 'select',function() {

Also to select the value you can just do .val();

window.location = $(this).val();


来源:https://stackoverflow.com/questions/13962824/make-select-option-selected-based-on-an-unordered-list-using-jquery

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!