问题
Is it possible to transclude one HTML element into multiple locations of a document, as it is in MediaWiki? I want to include elements inside other elements, without copying and pasting their content. I know that it's possible to embed web pages inside other web pages using iframes, but is there any reliable way to embed HTML elements inside other HTML elements, on the same page?
<p id = "p1">This is paragraph 1. </p>
<p id = "p2">
This is paragraph 2.
</p>
<p id = "p3">This is paragraph 3. It should contain paragraphs 1 and 2.
<!-- {{p1}} {{p2}} -->
</p>
回答1:
This is a bit of a hack, but it works in Firefox, Chrome, and Opera. Not tested in IE, don't have it on this laptop... let me know if it works in IE if you get a chance to test.
Put this in the document's head
, in a script
tag:
function transclude(elementId) {
var clone = document.getElementById(elementId).cloneNode(true),
placeholder;
clone.id = null;
document.write('<br id="__placeholder__">');
placeholder = document.getElementById('__placeholder__');
placeholder.parentNode.insertBefore(clone, placeholder);
placeholder.parentNode.removeChild(placeholder);
return transclude;
}
To transclude elements, use this:
<p id="p1">This is paragraph 1. </p>
<p id="p2">
This is paragraph 2.
</p>
<p id="p3">This is paragraph 3. It should contain paragraphs 1 and 2.
<script>transclude("p1")("p2")</script>
</p>
Notes:
ID attribute is removed from cloned elements.
Elements are transcluded as soon as the script containing the call to
transclude
runs, no waiting for the document to load. Because of the use ofdocument.write
, this will not work after the document has been loaded.We use a dummy placeholder element, a
<br>
, to prevent a side effect ofdocument.write
, where writing for example a<p>
after a<p>
that has been opened but not terminated causes the first tag to terminate prematurely.In other words, the tag name of the placeholder element should be different from the names of any unterminated outer tags, thus the self-terminating
<br>
tag.Transclusion function returns itself for chaining.
http://jsfiddle.net/bcWjE/1
回答2:
Using jQuery:
$(document).ready(function(){
$('#p3').html($('#p1').html()+$('#p2').html())
});
JsFiddle
回答3:
It may be more appropriate to use jQuery's .clone() method, which performs a deep copy of a DOM node, perserving things like bound methods.
Trivial example (from the docs) applying $('.hello').clone().appendTo('.goodbye');
to
<div class="container">
<div class="hello">Hello</div>
<div class="goodbye">Goodbye</div>
</div>
results in
<div class="container">
<div class="hello">Hello</div>
<div class="goodbye">
Goodbye
<div class="hello">Hello</div>
</div>
</div>
来源:https://stackoverflow.com/questions/15583024/how-to-transclude-html-elements-in-a-document