如何获取要显示下拉菜单的选定值

How to Get Selected Value to show for DropDown Menu

本文关键字:下拉菜单 显示 何获取 获取      更新时间:2023-09-26

我有一个下拉菜单,工作得很好,改变页面的部分完美无缺。问题是,当选择的页面被加载和显示,我需要它显示下拉菜单中选择的名称,因为它是活动的页面。我有以下代码:

       <div class="about-navDropWrapper">
            <select onchange="location = this.options[this.selectedIndex].value;">
                <?php 
                            if ( get_field('games_nav_drop_down_link', 'option') ):
                                while( has_sub_field('games_nav_drop_down_link', 'option') ) :
                        ?>
                        <option value="<?php echo get_sub_field('games_nav_drop_down_link_one', 'option'); ?>"><?php echo get_sub_field('games_nav_drop_down_name', 'option'); ?></option>
                        <?php 
                            endwhile;
                            endif;
                        ?>
            </select>
        </div>

有什么建议吗?

selected="selected"属性添加到所选页面的option元素中。您可以在jquery中通过查找您想要的元素值的<option>来做到这一点(注意,我假设values末尾的>是一个错字并将其删除):

例如我们想显示page3.html

var selected = "page3.html"; // Would be replaced with the page by location
$("#selectItem option[value='"+selected+"']").attr("selected", "selected");
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="about-navDropWrapper">
            <select id="selectItem">
                <option value="page1.html">Page 1</option>
                <option value="page2.html">Page 2</option>
                <option value="page3.html">Page 3</option>
                <option value="page4.html">Page 4</option>
            </select>
        </div>

请试试:

 <script>
        onload = function () {
            var thisPage = location.pathname.replace("/", "");
            document.getElementsByTagName("select")[0].value = thisPage;
        }
    </script>