如何在文档中包含HTML元素 [英] How to transclude HTML elements in a document

查看:90
本文介绍了如何在文档中包含HTML元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以像在MediaWiki中那样将一个HTML元素包含在文档的多个位置中?我想将元素包含在其他元素内,而不复制和粘贴它们的内容.我知道可以使用iframe将网页嵌入到其他网页中,但是有没有可靠的方法将HTML元素嵌入到同一页面上的其他HTML元素中?

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>

推荐答案

这有点麻烦,但是可以在Firefox,Chrome和Opera中使用.尚未在IE中进行测试,请不要在笔记本电脑上使用它...如果有机会进行测试,请告诉我它是否可以在IE中运行.

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.

将此文件放置在文档的head中的script标记中:

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>

注意:

  • ID属性已从克隆的元素中删除.

  • ID attribute is removed from cloned elements.

包含对transclude的调用的脚本运行后,即会立即将其包含在内,而无需等待文档加载.由于使用document.write,因此在文档加载后将无法使用.

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 of document.write, this will not work after the document has been loaded.

我们使用虚拟占位符元素<br>来防止document.write的副作用,其中在已打开但未终止的<p>之后写入例如<p>第一个标签过早终止.

We use a dummy placeholder element, a <br>, to prevent a side effect of document.write, where writing for example a <p> after a <p> that has been opened but not terminated causes the first tag to terminate prematurely.

换句话说,占位符元素的标签名称应与任何未终止的外部标签的名称不同,因此应与自终止的<br>标签相同.

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

这篇关于如何在文档中包含HTML元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆