选择菜单,使用JQuery选择url?
我有以下html:
HTML标记
还有一些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上找到url? 所以,如果我点击雅虎,它会把我带到yahoo.com?
谢谢你的帮助!
$('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; }) });
在主流浏览器上测试了工作演示
这应该这样做:
$('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())}); }); });
在创建选择时添加更改事件,并将用户发送到所选值。
var select=$(document.createElement('select')).insertBefore($(this).hide()).change(function(){ document.location.href = $(this).val(); });
尝试一下:
$('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中动态创建的。