选择了jQuery下拉菜单

时间:2014-02-04 03:01:03

标签: jquery drop-down-menu

我有这个下拉菜单,并且在更改时,window.location.href会发生变化,但是如何在页面更改时选择所选值?

<div class="iPhoneNav">
    <select class="iPhoneDropdown">
            <option value="/">Home</option>
            <option value="/services">Services</option>
            <option value="/about-us">About Us</option>
            <option value="/gallery">Gallery</option>
            <option value="/testimonials">Testimonials</option>
            <option value="/tours">Tours</option>
            <option value="/contact-us">Contact Us</option>
            <option></option>
    </select>
    <script type="text/javascript">
            (function($){

                    $(function(){
                            $('select').change(function(index){
                                    window.location.href = $(this).val();
                            });

                    });

            })(jQuery);     
    </script>

2 个答案:

答案 0 :(得分:2)

如果您使用此示例中的select,请尝试使用路径名设置值:

$(function(){
    $('.iPhoneDropdown').val(location.pathname);
});

答案 1 :(得分:0)

您可以在正文中存储所选选项的某些值或ID,或者使用“data”存储某些元素。为选项标签提供唯一ID。选择选项后,将所选选项“id”与数据一起存储。

试试这个,

<div class="iPhoneNav">
<select class="iPhoneDropdown">
        <option id="1" value="/">Home</option>
        <option id="2" value="/services">Services</option>
        <option id="3" value="/about-us">About Us</option>
        <option id="4" value="/gallery">Gallery</option>
        <option id="5" value="/testimonials">Testimonials</option>
        <option id="6" value="/tours">Tours</option>
        <option id="7" value="/contact-us">Contact Us</option>
        <option></option>
</select>
<script type="text/javascript">
        (function($){

                $(function(){

                        if($('body').data('selected_opt') != "" || $('body').data('selected') != 'undefined') {
                            var op_id = $('body').data('selected_opt');
                            $('select').find('option[id="' + op_id + '"]').attr('selected', true);    //you can also use prop instead of attr
                        }
                        $('select').change(function(index){
                            $('body').data('selected_opt', $(this).attr('id'));
                            window.location.href = $(this).val();
                        });

                });

        })(jQuery);     
</script>