最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - jQuery clone() isn't working - Stack Overflow

programmeradmin0浏览0评论

I seem to have broken the clone function somehow. My jQuery clone function is relatively simple, but doesn't seem to be working. I have two elements, and I'm trying to copy from one to the other:

<div id="copy"><span>Some stuff to copy.</span></div>

<div id="paste"></div>

jQuery:

$(document).ready(function(){
  $('#copy').clone().append('#paste');
});

You can see a codepen here:

I seem to have broken the clone function somehow. My jQuery clone function is relatively simple, but doesn't seem to be working. I have two elements, and I'm trying to copy from one to the other:

<div id="copy"><span>Some stuff to copy.</span></div>

<div id="paste"></div>

jQuery:

$(document).ready(function(){
  $('#copy').clone().append('#paste');
});

You can see a codepen here: http://codepen.io/anon/pen/NPrBRq

Share Improve this question asked Dec 19, 2014 at 16:51 alloyalloy 7661 gold badge14 silver badges24 bronze badges 3
  • 3 Two divs with the same id may have a lot to do with it – danronmoon Commented Dec 19, 2014 at 16:52
  • 1 Your goal isn't clear but you might want to use appendTo instead of append. Now you're appending (moving) #paste to a clone you don't put in the page, this can't achieve anything useful. – Denys Séguret Commented Dec 19, 2014 at 16:53
  • 3 I was about to say, I think you mean appendTo, not append – Phil Tune Commented Dec 19, 2014 at 16:54
Add a ment  | 

3 Answers 3

Reset to default 5

Should be:

$(document).ready(function(){
  $('#copy span').clone().appendTo('#paste');
});

Fundamentally, append() and appendTo() perform the same task, however, appendTo is used for appending to a specific element(which is, I believe, what you were going for). Read more here.

Also, your Pen did not have the jQuery library included.

Two problems with that code:

  1. You want to use appendTo, not append. a.append(b) appends the content b to the element a; a.appendTo(b) is the other way around, it appends a to b.

  2. You need to remove the id of the cloned element; if you don't, you create an invalid document, because ids must be unique

So:

$(document).ready(function(){
  $('#copy').clone().removeAttr("id").appendTo('#paste');
});

$(document).ready(function(){
  $('#copy').clone().removeAttr("id").appendTo('#paste');
});
<div id="copy"><span>Some stuff to copy.</span></div>
<div id="paste"></div>

<script src="https://ajax.googleapis./ajax/libs/jquery/1.11.1/jquery.min.js"></script>

You should append the cloned element to DOM

$(document).ready(function(){
  $('#copy').clone().appendTo('#paste');
});
发布评论

评论列表(0)

  1. 暂无评论