jQuery - 将每个html()类值设置为另一个元素

时间:2016-04-15 09:59:53

标签: jquery

我有以下代码: -

HTML

<div id="nottingham-park-wrapper">
  <div id="notts-main-court" class="icon-wrapper">
    <span class="park-marker"></span>
  </div>
  <span id="notts-main-court-info" class="notts-info">
  <h2 class="infobox-title">TITLE 1</h2>
  <p class="infobox-desc">TEXT INFO 1</p>
  </span>
  <div id="notts-dodgeball" class="icon-wrapper">
    <span class="park-marker"></span>
  </div>
  <span id="notts-dodgeball-info" class="notts-info">
  <h2 class="infobox-title">TITLE 2</h2>
  <p class="infobox-desc">TEXT INFO 2</p>
  </span>
</div>

<hr>

<span class="mobile-notts-info"></span>

的jQuery

    jQuery(".notts-info").each(function(index) {
      var notts_info = jQuery(this).html();
      jQuery(this).html('');
      jQuery(".mobile-notts-info").html(notts_info);
    });

VIEW JSFIDDLE

基本上我想在.notts-info

中移动每个.mobile-notts-info html

目前它只移动每个循环中的最后一个值,我怎样才能获得所有值? (在这个例子中只有2个,实际版本中还有很多,这就是为什么我要使用每个元素而不是单独执行每个元素)

提前致谢!

1 个答案:

答案 0 :(得分:3)

.html()删除现有内容并添加新内容。由于目标父级中只有最后一个内容可用。您需要使用.append()代替.html()来保留现有内容并将新内容附加为父级的最后一个孩子:

jQuery(".mobile-notts-info").append(notts_info);

<强> Working Demo

但是,您不需要迭代元素,您可以将代码缩减为:

jQuery(".mobile-notts-info").append(jQuery(".notts-info"));

<强> Optimised Code working Demo