jQuery Append element from iframe to it's body parent window.
I have
elm.appendTo('#wrap');
where elm
is a jquery object of the clicked image inside iframe. I want to append that image to a <div id="wrap">
where #wrap
is a div in the body of the page outside iframe. So basically when i double cli开发者_StackOverflow中文版ck on an image inside iframe, i want that image to append to <body>
outside iframe. Both body and iframe link are on the same domain.
Provided that the frame and its parent are at the same domain. See SOP
Execute either of the following lines from within the iframe (
parent
can be replaced by top
, if the parent document is in the top window):
//If the parent document doesn't have JQuery:
elm.appendTo(parent.document.getElementById("wrap"));
//Only if JQuery is included at the parent
elm.appendTo(parent.$("#wrap"));
parent.$("#wrap").append(elm);
If you want to grab the element inside the frame, from the context of the parent, use either of the following:
Assume #elm
to be the ID of your image.
// If JQuery is defined at the frame AND the parent (current document)
$("#wrap").append(frames[0].$("#elm"));
frames[0].$("#elm").appendTo($("#wrap"));
frames[0]
refers to the first frame within the current document. If you've set a name
attribute on your frame, you can also use frames.frame_name
, or frames["frame_name"]
.
Final example: Adding a
click
event listener to the elm
JQuery (image) object:
elm.click(function(){
parent.$("#wrap").append(this);
})
Try going at it from the other way: from the parent window, find the element you want to append to and then use .append()
and select the element in the iframe. For example:
$("#wrap").append($("iframe #myElement"));
精彩评论