javascript 如何使用jquery附加一个div
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19620677/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to append a div using jquery
提问by Relm
Is there anyway i can achieve the following by appending "div #B" from somewhere else like from another page or from somewhere in the body rather than writting it inside this script itself and not face same origin policy issues like when using JQuery's Load?
无论如何,我是否可以通过从其他地方(例如从另一个页面或正文中的某处)附加“div #B”来实现以下目标,而不是将其写入该脚本本身,并且不会像使用 JQuery 的 Load 那样面临同源策略问题?
$('#A').append("<div id='B'><span><img src='i1.png'></span></div>");
回答by TrungDQ
You can use this to append an element's HTML in your body
您可以使用它在您的正文中附加元素的 HTML
$('#A').append($('#someelement').html());
This won't work with cross origin iframes because of same-origin policy. But you can get the HTML from another page by using AJAX, as long as the URL is in the same origin.
由于同源策略,这不适用于跨源 iframe。但是您可以使用 AJAX 从另一个页面获取 HTML,只要 URL 位于同一来源。
回答by ReQwire
I'm sorry but if you wish to append a div, you must be able to specify it's contents and styles.
抱歉,如果您想附加一个 div,您必须能够指定它的内容和样式。
If you want to extract it from a div on the page do this:
如果要从页面上的 div 中提取它,请执行以下操作:
var loadAble = $('#YourDivName').html();
$('#A').append("<div class="B"></div>");
$('#A .B').html(loadAble);
Remember to replace YourDivName respectively!
记得分别替换YourDivName!
I know you said not to use .load(), but here goes anyway:
我知道你说过不要使用 .load(),但这里还是这样:
$('#A').append("<div class="B"></div>");
$('#A .B').load("yourFileGoesHere.html#YourDivName");
An alternative (untested) is to write:
另一种(未经测试)是写:
var B = $('#A').append("<div class="B"></div>");
B.load("yourFileGoesHere.html#YourDivName");