假设我有一个在div或UL下的项目列表。我想采用具有相同title属性的所有列表项,并在其周围包裹一个UL。不过,下一部分是我希望UL处于具有相同属性的LI下。因此,我正在尝试基本分组。

所以...我从...开始

<li>Insurance</li>
<li>Education</li>
<li>Sports</li>
<li>Construction</li>
<li title ="Insurance">Malpractice</li>
<li title ="Construction">Carpentry</li>
<li title ="Education">College</li>
<li title ="Insurance">Automobile</li>
<li title ="Education">High School</li>
<li title ="Construction">Iron Worker</li>

我想去......
<li>Insurance
    <ul>
         <li title ="Insurance">Malpractice</li>
         <li title ="Insurance">Automobile</li>
   </ul>
</li>
<li>Education
    <ul>
         <li title ="Education">College</li>
         <li title ="Education">High School</li>
   </ul>
</li>
<li>Sports</li>
<li>Construction
    <ul>
         <li title ="Construction">Carpentry</li>
         <li title ="Construction">Iron Worker</li>
   </ul>
</li>

任何帮助,将不胜感激。显然对于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 = $('<ul></ul>');
    // ... fill it and ...
    children.appendTo(ul);
    // ... append it to the original li element
    ul.appendTo(li);
  }
});

jQuery文档: :not() [title] each() appendTo()

10-05 20:52
查看更多