附加到最近的Jquery

时间:2016-02-12 09:56:06

标签: jquery

我有这段代码:

$('.main_image a').each(function() {
	var main_image = $(this).clone();
	var bloc = $(this).closest('.item-content .bloc_image');
	bloc.append(main_image);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="item">
  <span class=" main_image bloc_image">
    <a href="#"></a>
  </span>
  <div class="item-content">
    <div class="bloc_image">
      <a href="#"></a>
      <a href="#"></a>
    </div>
  </div>
</div>

<div class="item">
  <span class=" main_image bloc_image">
    <a href="#"></a>
  </span>
  <div class="item-content">
    <div class="bloc_image">
      <a href="#"></a>
      <a href="#"></a>
    </div>
  </div>
</div>

我希望每个.item .main_image克隆自身的链接并进入.bloc_image

我在Jquery中尝试但它不起作用。

感谢您的帮助!

2 个答案:

答案 0 :(得分:2)

您遇到的问题是closest()仅查看DOM上的父元素。 .item-content .bloc_image是兄弟姐妹的孩子。在这种情况下,您应该使用closest()来获取最近的公共父级,然后使用find()。试试这个:

&#13;
&#13;
$('.main_image a').each(function() {
  var $main_image = $(this).clone();
  $(this).closest('.item').find('.item-content .bloc_image').append($main_image);
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="item">
  <span class=" main_image bloc_image">
    <a href="#">main_image</a>
  </span>
  <div class="item-content">
    <div class="bloc_image">
      <a href="#">bloc_image</a>
      <a href="#">bloc_image</a>
    </div>
  </div>
</div>

<div class="item">
  <span class=" main_image bloc_image">
    <a href="#">main_image</a>
  </span>
  <div class="item-content">
    <div class="bloc_image">
      <a href="#">bloc_image</a>
      <a href="#">bloc_image</a>
    </div>
  </div>
</div>
&#13;
&#13;
&#13;

答案 1 :(得分:0)

获取closest('.item-content'),然后使用find()

获取内部bloc_image

$('.main_image a').each(function() {
  var main_image = $(this).clone();
  var bloc = $(this).closest('.item').find('.item-content .bloc_image').first();
console.log(bloc);
  bloc.append(main_image);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="item">
  <span class=" main_image bloc_image">
    <a href="#">asd</a>
  </span>
  <div class="item-content">
    <div class="bloc_image">
      <a href="#">asd</a>
      <a href="#">asd</a>
    </div>
  </div>
</div>

<div class="item">
  <span class=" main_image bloc_image">
    <a href="#">asdasd</a>
  </span>
  <div class="item-content">
    <div class="bloc_image">
      <a href="#">asdasd</a>
      <a href="#">asdasdasd</a>
    </div>
  </div>
</div>