javascript - 如何获取所选值以显示下拉菜单

标签 javascript jquery html css

我有一个效果很好的下拉菜单,更改页面的部分是否完美无缺。问题是当选定的页面被加载和显示时,我需要它在下拉菜单中显示选择的名称,因为它是事件页面。我有以下代码:

       <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"所选页面的选项元素的属性。您可以在 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>

关于javascript - 如何获取所选值以显示下拉菜单,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32997118/

相关文章:

javascript - 仅针对某些键从数组映射数据(未过滤)

html - 绝对定位按钮未定位在其父 DIV 中

javascript - 获取 css 最高值作为数字而不是字符串?

javascript - Jquery(输入/文本区域).val() : how is it adding content without changing the DOM?

Javascript - 传递包含变量的 html 字符串作为参数

javascript - 如何让这个 jQuery Youtube 弹出窗口在我的本地网站上运行?

javascript - 当用户更改 slider 值时,如何在没有任何按钮的情况下提交 slider 值?

javascript - 从字符串中获取多个字节的更简单方法?

javascript - 固定位置表格行标签

html中的Javascript - 在另一个单引号内使用单引号