【问题标题】:Change selected drop down option depending on page (menu)根据页面(菜单)更改选定的下拉选项
【发布时间】:2013-03-05 14:31:40
【问题描述】:

我在我的 WP 主题中使用下拉菜单,并使用选择框。在选择新选择选项时,页面更改页面。但是,当呈现新页面时,选择菜单中的默认选项仍然是“起始页”(第一个)。

我可以做些什么来改变当前页面?

header.php:

<div id="navigation" role="navigation">

    wp_nav_menu(array(
        'container' => false,
        'menu_id' => 'nav',
        'theme_location' => 'primary', // your theme location here
        'walker'         => new Walker_Nav_Menu_Dropdown(),
        'items_wrap'     => '<select>%3$s</select>',
        'fallback_cb'    => 'bp_dtheme_main_nav'
    ));


    class Walker_Nav_Menu_Dropdown extends Walker_Nav_Menu{
        function start_lvl(&$output, $depth){
            $indent = str_repeat("\t", $depth);
            }

        function end_lvl(&$output, $depth){
            $indent = str_repeat("\t", $depth);
        }

        function start_el(&$output, $item, $depth, $args){
            $item->title = str_repeat("&nbsp;- ", $depth).$item->title;

            parent::start_el($output, $item, $depth, $args);

            $href =! empty( $item->url ) ? ' value="'   . esc_attr( $item->url ) .'"' : '#';

            $output = str_replace('<li', '<option '.$href, $output);
        }

        function end_el(&$output, $item, $depth){
            $output .= "</option>\n"; // replace closing </li> with the option tag
        }
    } ?>

</div>

jquery:

$("#navigation select").on('change', function() {
    window.location = jq(this).find("option:selected").val();
});

【问题讨论】:

    标签: wordpress select drop-down-menu menu option


    【解决方案1】:

    由于每个选项的值都是一个 URL,因此只需遍历每个选项并与当前页面 URL 进行比较即可。如果它们相同,请将选项的属性设置为 selected。

    $("#navigation option").each(function () {
        if ($(this).val() === window.location.toString()) {
            $(this).prop('selected', true);
        }
    });
    

    【讨论】:

    • 谢谢!如果我将 === 更改为 ==,它会起作用。显然值和 url 在某些方面略有不同(即使它们在 console.logging 时看起来完全相同)
    • @holyredbeard 是的,抱歉,window.location 是一个对象。不要使用$(this).val() == window.location 并强制类型,而是使用$(this).val() === window.location.toString()。我将编辑我的答案以反映这一点。
    猜你喜欢
    • 1970-01-01
    • 2019-01-25
    • 2022-11-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多