WrapAll()在具有多个外观的多个类上

时间:2016-11-21 18:17:02

标签: javascript jquery html wrapall

让我们说这是我的HTML

<ul class="products>
<li class="product">
<div class="product-title></div>
<div class="product-thumbnail></div>
<div class="product-price></div>
<div class="product-discription></div>
</li>
<li class="product">
<div class="product-title></div>
<div class="product-thumbnail></div>
<div class="product-price></div>
<div class="product-discription></div>
</li>
</ul>

现在我想将.product-thumbnail.product-price包裹在

<div class="left"></div>

喜欢这个

  <ul class="products>
       <li class="product">
        <div class="product-title></div>
        <div class="left">
         <div class="product-thumbnail></div>
         <div class="product-price></div>
        </div>
        <div class="product-discription></div>
       </li>

       <li class="product">
        <div class="product-title></div>
        <div class="left">
         <div class="product-thumbnail></div>
         <div class="product-price></div>
        </div>
        <div class="product-discription></div>
       </li>
    </ul>

如果我只有一个列表项

,这个代码可以解决问题
$(".product-thumbnail, .product-price").wrapAll("<div class='left'></div>");

我在each().product-thubnail上尝试.product-price,但没有结果..

有谁知道我如何才能做到这一点或如何使用each()完成?

1 个答案:

答案 0 :(得分:2)

使用each()方法迭代.product-title并使用add()方法与下一个元素结合使用。

&#13;
&#13;
$('.product-title').each(function() {
  $(this).add($(this).next()).wrapAll('<div class="left"></div>')
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul class="products">
  <li class="product">
    <div class="product-title"></div>
    <div class="product-thumbnail"></div>
    <div class="product-price"></div>
    <div class="product-discription"></div>
  </li>
  <li class="product">
    <div class="product-title"></div>
    <div class="product-thumbnail"></div>
    <div class="product-price"></div>
    <div class="product-discription"></div>
  </li>
</ul>
&#13;
&#13;
&#13;

或迭代li并通过提供上下文来获取元素中的两个类。

&#13;
&#13;
$('.product').each(function() {
  $('.product-title,.product-thumbnail', this).wrapAll('<div class="left"></div>')
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul class="products">
  <li class="product">
    <div class="product-title"></div>
    <div class="product-thumbnail"></div>
    <div class="product-price"></div>
    <div class="product-discription"></div>
  </li>
  <li class="product">
    <div class="product-title"></div>
    <div class="product-thumbnail"></div>
    <div class="product-price"></div>
    <div class="product-discription"></div>
  </li>
</ul>
&#13;
&#13;
&#13;