将每个元素添加到其相应的相邻元素

时间:2016-03-16 22:48:14

标签: jquery

我有一个文章列表,每个文章都有一个.cat-title和一个.other。我正在尝试将每个.cat-title添加到其各自的.other。这是我尝试过的,但我很难理解.each函数。

jQuery( document ).ready(function() {

jQuery('.cat-title').each(function() {
  jQuery(this).prependTo(.other);
}

});

标记:

<div>

  <span class="cat-title>Test</span>
  <a class="other" href="/">Link</a>

  <span class="cat-title>Test</span>
  <a class="other" href="/">Link</a>

  <span class="cat-title>Test</span>
  <a class="other" href="/">Link</a>

  </div>

</div>

期望的结果:

<div>

  <a class="other" href="/">Link
    <span class="cat-title>Test</span>
  </a>

  <a class="other" href="/">Link
    <span class="cat-title>Test</span>
  </a>

  <a class="other" href="/">Link
    <span class="cat-title>Test</span>
  </a>

</div>

2 个答案:

答案 0 :(得分:0)

尝试将选择器放在每个函数中:

$。each(jQuery('。cat-title'),function(index,value){     $(value).prependTo('。other a');   });

答案 1 :(得分:0)

我建议:

jQuery('.cat-title').each(function(){
  // caching the variable:
  let el = jQuery(this);

  // prepending the current element of the
  // collection to the element found via
  // the selector passed to the method,
  // which traverses from the current element
  // to its next <a> element sibling, returning 
  // that element to the method:
  el.prependTo(el.next('a'));
});

或者:

// finds the <a> elements first, and then
// uses the anonymous function of the 
// prepend() method:
jQuery('a').prepend(function(){
  // within the method's function 'this'
  // refers to the <a> element over which
  // the method iterates.

  // here we find the previous sibling,
  // the <a> element, if it matches
  // the selector, returning that element
  // to the method:
    return jQuery(this).prev('.cat-title');
});

参考文献: