【问题标题】:Replace each tag p by tag li and around group li by tag ul用标签 li 替换每个标签 p,用标签 ul 替换组 li
【发布时间】:2012-03-13 16:50:22
【问题描述】:

这里是html:

<section class="category">
        <p><a href="product-list.html">Lorem ipsum dolor sed diam</a></p>
        <p><a href="product-list.html">Lorem ipsum dolor sed diam</a></p>
        <p><a href="product-list.html">Lorem ipsum dolor sed diam</a></p>
        <p><a href="product-list.html">Lorem ipsum dolor sed diam</a></p>
      <section class="clear"></section>
    </section>

如何替换标签 p --> li 并用标签 ul 包装组 li 。我需要它:

   <section class="category">
      <ul>
        <li><a href="product-list.html">Lorem ipsum dolor sed diam</a></li>
        <li><a href="product-list.html">Lorem ipsum dolor sed diam</a></li>
        <li><a href="product-list.html">Lorem ipsum dolor sed diam</a></li>
        <li><a href="product-list.html" >Lorem ipsum dolor sed diam</a></li>
      </ul>
      <section class="clear"></section>
</section>

【问题讨论】:

  • 提示:不需要 clear-element (section.clear),只需使用简单的 clearfix-solutions 之一(父级上的overflow: hidden; 就足够了)。另外,如果您坚持使用 html 元素来清除浮动,为什么要使用语义 section 元素? section 不是在这里替换 div,它在这里为我们过去使用 div 的一些东西提供意义。但是,在清除元素的情况下,section 不合适,div 合适。

标签: jquery html jquery-ui jquery-selectors


【解决方案1】:
jQuery('.category').each(function(){
    var c = jQuery(this);
    var ul = jQuery('<ul/>');
    c.find('p').each(function(){
        var p = jQuery(this);
        ul.append(jQuery('<li/>').append(p.children()));
    }).remove();
    c.prepend(ul);        
});

【讨论】:

    【解决方案2】:

    在你的 jQuery 中这样做

        $("p").each(function () {
     $(this).replaceWith("<li>" + $(this).html() + "</li>");
      });
    

    提高您的接受率。

    【讨论】:

      【解决方案3】:

      你可以结合使用

      http://api.jquery.com/replaceWith/

      http://api.jquery.com/wrapAll/

      $(".category p").wrapAll("<ul>").replaceWith(function() {
          return $("<li></li>").append($(this).html());
      });
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-06-02
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-09-07
        • 1970-01-01
        相关资源
        最近更新 更多