将 HREF 添加到 JQuery 动态填充的选择

Adding a HREF to a JQuery Dynamically Populated Select

本文关键字:填充 选择 动态 JQuery HREF 添加      更新时间:2023-09-26

我有一个基于表单的菜单,它会自动使用主导航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");
});

谁能告诉我如何做到这一点?

谢谢。

您可以在当前代码中添加 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');