【问题标题】:Convert current page class to select menu 'selected'将当前页面类转换为选择菜单“已选择”
【发布时间】:2011-07-11 01:07:13
【问题描述】:

我目前有一个 jQuery 函数,可以将 wp_list_pages 转换为选择菜单,当您选择页面时,该菜单会导航到所选页面。我想知道的是我可以使用“current_page_item”类并将其转换为将当前页面设置为“选定”选项吗?我当前的代码如下:

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

【问题讨论】:

  • 代码不工作?如果没有,什么不起作用?你能给我们一个 JsFiddle.net 上的演示链接吗?

标签: javascript jquery html wordpress


【解决方案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);
    });
});

【讨论】:

  • 在第 3 行生成错误“$('ul.selectdropdown')[0] is undefined”。
  • 那是你的代码人。我添加的只是window.location.href == $(this).attr('href')) 条件
  • 如果代码对您有用,您介意单击我的答案旁边的复选标记以便我获得信用吗?这就是我们在网站上获得积分的方式 :) 谢谢!
猜你喜欢
  • 1970-01-01
  • 2019-07-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-07-08
  • 2016-01-28
  • 2011-01-03
相关资源
最近更新 更多