创建< select>从列表中-缩进子项? [英] Create <select> from list - indent child items?

查看:90
本文介绍了创建< select>从列表中-缩进子项?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个UL LI菜单,当您在手机上查看时,它会变成一个选择下拉列表.

I have a UL LI menu that I am turning into a select dropdown when you're viewing it on a mobile.

我现在想缩进子项,例如

I want to now indent child items e.g

  • 列出项目1
  • -子项1
  • ----儿童儿童项目1
  • -子项2
  • 列出项目2

而不是单行列出.

我很高兴只添加nbsp来使事情变得容易-或更合适的话添加类和CSS.

I'm happy to just add nbsp to keep things easy - or add classes and CSS if more suitable.

我当前用于生成选择的代码是:

The code I am currently using to generate the select is:

$("<select />").appendTo("#primary-nav");

  $("<option />", {
     "selected": "selected",
     "value"   : "",
     "text"    : "Go to..."
  }).appendTo("#primary-nav select");

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

  $("#primary-nav select").change(function() {
    window.location = $(this).find("option:selected").val();
  });  

其生成的菜单的构建方式如下:

The menu it is generating from is built like:

<ul>
  <li><a>Item 1</a>
      <ul>
          <li><a>Child Item 1</a>
              <ul>
                  <li><a>Child Item 1</a></li>
              </ul>
          </li>
          <li><a>Child Item 2</a></li>
      </ul>
  </li>
  <li><a>Item 2</a></li>
</ul>

这是一个带有示例的小提琴: http://jsfiddle.net/C5S32/

Here is a fiddle with an example: http://jsfiddle.net/C5S32/

推荐答案

这应该做您想要的,并且可以自定义. http://jsfiddle.net/C5S32/7/

This should do what you want, and it's pretty customizable. http://jsfiddle.net/C5S32/7/

var options = '<option selected>Go to...</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 />').append(options).appendTo('#primary-nav');

请注意,在您的代码中,您多次添加了东西.最好将所有内容都附加在一个调用中,以避免过多的重排.

As a side note, in your code you're appending stuff many times. It's better to append everything in one call to avoid excessive reflows.

这篇关于创建&lt; select&gt;从列表中-缩进子项?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆