javascript - Make select option selected based on an unordered list using jQuery - Stack Overflow

I've converted my unordered list into a select option list, however I'm not sure how can I ma

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

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(); 
Share Improve this question asked Dec 19, 2012 at 23:13 calebocalebo 3,44210 gold badges48 silver badges69 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 6

You can use hasClass method:

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

http://jsfiddle/5V5rY/

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

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745646125a4637982.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信