代码之家  ›  专栏  ›  技术社区  ›  Keith Donegan

选择菜单,在使用jquery选择时转到url?

  •  2
  • Keith Donegan  · 技术社区  · 16 年前

    我有以下HTML:

    HTML标记

    <ul id="test">
       <li><a href="http://www.yahoo.com">yahoo</a></li>
       <li><a href="http://www.google.com">Google</a></li>
    </ul>
    

    还有一些js代码:

    jquery/javascript代码

    $('ul#test').each(function()
    {
       var select=$(document.createElement('select')).insertBefore($(this).hide());
       $('>li a', this).each(function()
       { 
     option=$(document.createElement('option')).appendTo(select).val(this.href).html($(this).html());
       });
    });
    

    这段代码生成了一个select下拉菜单,正是我想要的,但我的问题是如何转到select上的url?如果我点击雅虎,它会把我带到Yahoo.com?

    谢谢你的帮助!

    5 回复  |  直到 16 年前
        1
  •  7
  •   Reigel Gallarde    16 年前
    $('ul#test').each(function()
    {
       var select=$(document.createElement('select')).insertBefore($(this).hide());
       $('>li a', this).each(function()
       { 
     option=$(document.createElement('option')).appendTo(select).val(this.href).html($(this).html());
       });
       select.change(function(){
        //alert('url = ' + this.value );
        window.location.href = this.value;
      })
    });
    

    测试工作 demo 在主要浏览器上。

        2
  •  1
  •   Luis    16 年前

    这应该做到:

     $('ul#test').each(function()
        {
           var select=$(document.createElement('select')).insertBefore($(this).hide());
           $('>li a', this).each(function()
           { 
         option=$(document.createElement('option')).appendTo(select).val(this.href).html($(this).html());
         option.click(function(){window.location = $(this).val())});
           });
        });
    
        3
  •  1
  •   Yisroel    16 年前

    在select的创建中添加一个change事件,并将用户发送到selected值。

    var select=$(document.createElement('select')).insertBefore($(this).hide()).change(function(){
      document.location.href = $(this).val();
    }); 
    
        4
  •  1
  •   Sarfraz    16 年前

    试试看:

    $('ul#test').each(function()
    {
       // also give the select an id
       var select = $(document.createElement('select')).attr('id', 'myselect').insertBefore($(this).hide());
    
       $('>li a', this).each(function()
       { 
         option=$(document.createElement('option')).appendTo(select).val(this.href).html($(this).html());
       });
    });
    

    现在重新定向…

    $(function(){
      $('#myselect').live('change', function(){
        document.location.href = $(this).val();
      });
    });
    

    这个 live() 方法,因为选择框是在dom中动态创建的。

        5
  •  1
  •   Homem Robô    16 年前
    <select name="dest" class="selec" onchange='document.location.href=this.options[this.selectedIndex].value;'>
    
    推荐文章