Jquery 将ul转换为和,并保持等级

Jquery 将ul转换为和,并保持等级,jquery,Jquery,我尝试将菜单ul和lis转换为移动设备的选择和选项。我想保留已经存在的用于s元素的类。我可以将它们转换,但我不知道如何将类从li保持为option。我该怎么办 jQuery(document).ready(function ($) { if ($(window).width() < 639) { $('ul#nav').each(function () { var list = $(this),

我尝试将菜单ul和lis转换为移动设备的选择和选项。我想保留已经存在的用于s元素的类。我可以将它们转换,但我不知道如何将类从li保持为option。我该怎么办

jQuery(document).ready(function ($) {
       if ($(window).width() < 639) {
           $('ul#nav').each(function () {
               var list = $(this),
                   select = $(document.createElement('select')).insertBefore($(this).hide());

               $('>li a', this).each(function () {
                   var target = $(this).attr('target'),
                       option = $(document.createElement('option'))
                           .appendTo(select)
                           .val(this.href)
                           .html($(this).html())
                           .click(function () {
                           if (target === '_blank') {
                               window.open($(this).val());
                           } else {
                               window.location.href = $(this).val();
                           }
                       });
               });
               list.remove();
           });
       }
   });
你可以使用li获得一个参考

类是一个与目标类似的属性。只需在li上使用attr获取类,然后在选项上使用attr保存它


我不会给您代码,因为您最好自己编写。

使用您提供的代码,您可以尝试以下操作:

$('>li a', this).each(function() {
    var target = $(this).attr('target'),
    var classes = $(this).parent('li').attr('class'), //store the classes in the element
    option = $(document.createElement('option'))
        .appendTo(select)
        .val(this.href)
        .addClass(classes) //add the classes to the new option element
        .html($(this).html())
        ...
试试这个

var cls= $(this).attr('class')
将该类添加到选项


在$'>LIA'中使用addClass$this.attr'class',this each循环,$this.closest'li'。attr'class'获取LIHOY$document.createElement'option'的类,而不是$?如果您使用的是jQuery,请始终如一地使用它。好的,很好,我使用了$this。最接近的'li'。attr'class',将其存储在一个变量中并使用.addClass.@LucienDubois如果锚点是li的直接子级,您也可以使用。父级我使用的最接近是出于安全考虑,因为我看不到您拥有的html我使用了$this.closest'li.attr'class'而不是var class=$this.attr'class',它可以工作!
$(document.createElement('option'))
                           .appendTo(select)
                           .val(this.href)
                           .html($(this).html()).addClass(cls)