4

假设这是我的 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()

4

1 回答 1

2

迭代.product-titleusingeach()方法并与紧邻的下一个元素 usingadd()方法结合。

$('.product-title').each(function() {
  $(this).add($(this).next()).wrapAll('<div class="left"></div>')
});
<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>


或者通过提供上下文遍历li并获取元素中的两个类。

$('.product').each(function() {
  $('.product-title,.product-thumbnail', this).wrapAll('<div class="left"></div>')
});
<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>

于 2016-11-21T18:20:57.703 回答