我正在尝试为移动版本制作经典下拉菜单的第二个版本,通过复制它的元素并将它们放在带有此代码的选择框中,但我希望我保留原始菜单,而不是替换它,只需在选择框中复制它。然后,我将隐藏它并使其仅对移动设备可见。
所以我的问题是如何保留原始菜单并将其复制到选择框? 我很抱歉,但我必须这样问,因为我刚开始学习jquery ..
$('table.topMenu tr').each(function(){
var list=$(this),
select=$(document.createElement('select')).insertBefore($(this).hide()).change(function(){
window.location.href=$(this).val();
});
$('>td a', this).slice(2).each(function(){
var option=$(document.createElement('option'))
.appendTo(select)
.val(this.href)
.html($(this).html());
if($(this).parent().attr('id') === 'tm_active'){
option.attr('selected','selected');
}
});
});
答案 0 :(得分:1)
似乎你的代码唯一错误就是你试图以奇怪的方式选择一些后代元素。
$('table.topMenu tr').each(function(){
var list=$(this),
select=$(document.createElement('select')).insertBefore($(this).hide()).change(function(){
window.location.href=$(this).val();
});
// You need to get the child <td>'s of your list, which you can do using .find()
// on the element you want to find child elements in
list.find('td a', this).slice(2).each(function(){
var option=$(document.createElement('option'))
.appendTo(select)
.val(this.href)
.html($(this).html());
if($(this).parent().attr('id') === 'tm_active'){
option.attr('selected','selected');
}
});
});
此处的代码是http://jsfiddle.net/andyface/T2k6w/
的代码希望这能满足您的需求