0

選択ボックスを使用して、WP テーマでドロップダウン メニューを使用しています。いくつかの jQuery の助けを借りて、新しい選択オプションが選択されるとページが変わります。ただし、新しいページがレンダリングされるとき、選択メニューのデフォルト オプションは「開始ページ」(最初のページ) のままです。

現在のページに 1 つの変更を加えるにはどうすればよいですか?

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

1 に答える 1

2

各オプションの値は URL であるため、各オプションをループして現在のページ URL と比較するだけです。それらが同じである場合は、オプションのプロパティを選択済みに設定します。

$("#navigation option").each(function () {
    if ($(this).val() === window.location.toString()) {
        $(this).prop('selected', true);
    }
});
于 2013-03-05T14:45:51.593 に答える