jQuery/JS:复制类的内容并将其打印到页面上的其他地方

jQuery/JS: Copy the contents of a class and print it somewhere else on the page

本文关键字:打印 其他 JS 复制 jQuery      更新时间:2023-09-26

我有一个名为test-parent的类,如下所示,我想复制两个UL元素的内容,并将内容放在页面上的其他地方。

   <div class="test-parent">
    <hr>
    <strong>
    <ul style="list-style-type:none">
    <ul style="list-style-type:none">
    </div>

我的jQuery看起来像这样:

(function($) {
    $( document ).ready(function() {
        $( ".options_group").prepend( " <p>Test</p>" );
    });
}(jQuery));

本质上,我所需要做的就是将类中的两个UL元素预先添加到options_group类中。有人知道我该如何做到这一点吗?感谢

尝试一下,只需使用each()和clone函数()即可实现圆顶。正如您所说,您需要在其他地方使用ul元素,或者如果您只需要ul中的内容,则需要相应地修改

(function($) {
    $( document ).ready(function() {
        //$( ".options_group").prepend( " <p>Test</p>" );
        $('.test-parent ul').each(function(){
          $( ".options_group").append($(this).clone());
        });   
    });
}(jQuery));
ul{
   background:red;
   height:100px;
    width:100px;
}
.options_group{
  clear:both;
  border:1px solid black; 
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
   <div class="test-parent">
    <hr>
     <strong>
     <ul style="list-style-type:none">1</ul>
     <ul style="list-style-type:none">2</ul>
      </strong>
    </div>
 <div class="options_group">
</div>

您可以简单地使用jQuerys克隆函数来克隆uls:

$(function() {
  $(".copy").prepend($(".test-parent ul").clone());
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="test-parent">
  <hr/>
  <ul style="list-style-type:none">
    <li>item</li>
  </ul>
    <ul style="list-style-type:none">
    <li>item 2</li>
    </ul>
</div>
<div class="copy">
</div>