jQuery: Copying an Embedded Tweet's HTML

2019-09-16 03:40发布

问题:

Say I have an embedded tweet inside a div:

<div id="tweet">
    <blockquote class="twitter-tweet"><p>A lion would never cheat on his wife. But a Tiger Wood.</p>&mdash; Puns (@omgthatspunny) <a href="https://twitter.com/omgthatspunny/status/301482080490115072">February 13, 2013</a></blockquote>
    <script async src="//platform.twitter.com/widgets.js" charset="utf-8"></script>
</div>

<div id="tweet-insert"></div>

And I want to copy the tweet and insert it into another div:

var tweetHtml = $("#tweet").html();
$("#tweet-insert").html(tweetHtml);

Here is a fiddle.

This doesn't work and it makes me :(

Any idea on a fix?

回答1:

You can use jQuery's .clone() like this:

var tweetCopy = $("#tweet").clone();
$("#tweet-insert").append(tweetCopy);

jsFiddle: http://jsfiddle.net/jfriend00/9Segq/



回答2:

the script loads asynchronous, so it may happen that it's not loaded yet when you try to copy the contents.

Copy the contents when the load-event of the script fires: http://jsfiddle.net/doktormolle/MSfvT/