0

我有一个基于表单的菜单,它会自动使用主要导航 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 += '&ndash;&nbsp;';
                        }
                    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>

我需要以某种方式将以下内容添加到上面,以便在单击所选选项时转到一个 url,而不是基于显示值的 url;

$("#primary-nav a").each(function() {
var el = $(this);
$("<option />", {
 "value"   : el.attr("href"),
"text"    : el.text()
}).appendTo("#primary-nav select");
});

谁能告诉我我该怎么做?

谢谢你。

4

1 回答 1

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 += '&ndash;&nbsp;';
    }
    options += '<option value="'+href+'">' + depthChar + text + '</option>';
});
$('<select id=\'mobile-menu\' />').append(options).appendTo('#mobile-nav');
于 2013-10-10T05:54:26.860 回答