jquery排序和组li元素
假设我有一个div或UL下的项目列表。 我想获取具有相同title属性的所有列表项并围绕它包装UL。 接下来的部分是我希望UL具有相同属性的LI。 所以,我正在努力分组。
所以….我开始……
Insurance Education Sports Construction Malpractice Carpentry College Automobile High School Iron Worker
我想要……
Insurance - Malpractice
- Automobile
Education - College
- High School
Sports Construction - Carpentry
- Iron Worker
任何帮助,将不胜感激。 显然是jquery和javascript世界的新手,所以我试图将我的大脑包裹起来。
// first we fetch all items without title attribute var topLevel = $('li:not([title])'); // for each of those... topLevel.each(function() { var li = $(this), // ... we get its text ... title = li.text(), // ... and other li elements with the corresponding title children = $('li[title="' + title + '"]'); // if there are any... if (children.length > 0) { // ... create an empty list ... var ul = $('
'); // ... fill it and ... children.appendTo(ul); // ... append it to the original li element ul.appendTo(li); } });
jQuery文档:: :not()
, [title]
, each()
, appendTo()
输入:
Insurance Education Sports Construction Malpractice Carpentry College Automobile High School Iron Worker
jQuery的:
$("#stuffs li").each(function(){ $("#stuffs li[title='"+$(this).text()+"']").appendTo($(this)).wrapAll("
"); });
输出:
- Insurance
- Malpractice
- Automobile
- Education
- College
- High School
- Sports
- Construction
- Carpentry
- Iron Worker
微笑 🙂
在这里演示
这应该工作
$('#id li:not([title])').append('
'); $('#id li[title]').each(function() { $(this).appendTo('#id li:contains(' + $(this).attr('title') + ') ul'); })
一个演示