我有一个基于表单的菜单,它会自动使用primary-nav UL的内容填充选择选项。它奇妙地增加了反映菜单位置的破折号。
但是,它不会填充UL内链接的HREF。
这是我的代码:
<script>
$(function() {
var options = '<option selected></option>';
$('#primary-nav').find('a').each(function () {
var text = $(this).text(),
depth = $(this).parent().parents('ul').length,
depthChar = '',
i = 1;
for (i; i < depth; i++) { depthChar += '– ';
}
options += '<option>' + depthChar + text + '</option>';
});
$('<select id=\'mobile-menu\' />').append(options).appendTo('#mobile-nav');
$("#primary-nav select").change(function() {
window.location = $(this).find("option:selected").val();
});
});
</script>
我需要以某种方式将以下内容添加到上面,以便在单击时所选选项转到网址,而不是基于显示值的网址;
$("#primary-nav a").each(function() {
var el = $(this);
$("<option />", {
"value" : el.attr("href"),
"text" : el.text()
}).appendTo("#primary-nav select");
});
任何人都可以告诉我如何做到这一点吗?
谢谢。
答案 0 :(得分:0)
您只需在当前代码中添加value属性:
$('#primary-nav').find('a').each(function () {
var text = $(this).text(),
href = $(this).attr('href'),
depth = $(this).parent().parents('ul').length,
depthChar = '',
i = 1;
for (i; i < depth; i++) {
depthChar += '– ';
}
options += '<option value="'+href+'">' + depthChar + text + '</option>';
});
$('<select id=\'mobile-menu\' />').append(options).appendTo('#mobile-nav');