2011-07-11 41 views
0

我目前有一個jQuery功能,可以將wp_list_pages轉換爲選擇菜單,當您選擇頁面時,該菜單將導航至所選頁面。我想知道的是,我可以使用「current_page_item」類&將此轉換爲將當前頁面設置爲「selected」選項?我當前的代碼如下:轉換當前頁面類以選擇'selected'菜單

$('li.current_page_item').attr('selected', 'selected'); 
alert($('ul.selectdropdown')[0].selectedIndex); 
$(function() { 
    $('ul.selectdropdown').each(function() { 
     var $select = $('<select />'); 
     $(this).find('a').each(function() { 
      var $option = $('<option />'); 
      $option.attr('value', $(this).attr('href')).html($(this).html()); 
      $select.append($option); 
      $select.change(function() { window.open($select.find(':selected').val(), '_top'); }); 
     }); 
     $(this).replaceWith($select); 
    }); 
}); 
+0

是代碼不工作?如果不是,哪些不起作用?你能給我們一個鏈接到JsFiddle.net上的演示嗎? –

回答

1

試試這個:

$('li.current_page_item').attr('selected', 'selected'); 
alert($('ul.selectdropdown')[0].selectedIndex); 
$(function() { 
    $('ul.selectdropdown').each(function() { 
     var $select = $('<select />'); 
     $(this).find('a').each(function() { 
      var $option = $('<option />'); 
      $option.attr('value', $(this).attr('href')).html($(this).html()); 

      // Check for current page 
      if(window.location.href == $(this).attr('href')) 
      { 
       $option.prop('selected',true).addClass('current_page_item'); 
      } 

      $select.append($option); 
      $select.change(function() { window.open($select.find(':selected').val(), '_top'); }); 
     }); 
     $(this).replaceWith($select); 
    }); 
}); 
+0

在第3行生成錯誤「$('ul.selectdropdown')[0]未定義」。 – Mike

+1

這就是你的代碼人。所有我添加的是'window.location.href == $(this).attr('href'))'condition – AlienWebguy

+0

Yikes - 半睡半醒!謝謝 - 該代碼做到了! – Mike