gpt4 book ai didi

javascript - 使用 Polymer importHref 动态加载 HTML 页面

转载 作者:行者123 更新时间:2023-11-29 16:57:30 25 4
gpt4 key购买 nike

我正在编写一个简单的元素,它使用 Polymer 1.0 的辅助函数 importHref() 加载 html 文件。页面加载,但我得到的不是 html 呈现到页面,而是 [object HTMLDocument]

当我记录成功的回调时,导入的页面被包裹在 #document 对象中(不确定这里的术语)。但是,信息都在控制台中。

所以,我的问题是:如何将 html 呈现到页面?

元素:

<dom-module id="content-loader">

<template>
<span>{{fileContent}}</span>
</template>

<script>

Polymer({

is: "content-loader",

properties: {
filePath: {
type: String
}
},

ready: function() {
this.loadFile();
},

loadFile: function() {
var baseUrl;

if (!window.location.origin)
{
baseUrl = window.location.origin = window.location.protocol + "//" + window.location.hostname + (window.location.port ? ':' + window.location.port: '');
}
else
{
baseUrl = window.location.origin;
}

//import html document and assign to fileContent
if(this.filePath)
{
this.importHref(baseUrl + this.filePath, function(file){
this.fileContent = file.target.import;
console.log(this.fileContent); //logs fine
},
function(error){
console.log(error);
});
}
}

});

</script>

正在使用中:

<content-loader file-path="/app/general/contact.html"></content-loader>

最佳答案

<span>{{fileContent}}</span>将呈现 fileContent转换为字符串,这就是为什么您会看到 [object HTMLDocument] (这就是你在 toString() 对象上调用 document 时得到的结果)。

一般来说,Polymer 不会让您绑定(bind)到 HTML 或节点内容,因为它存在安全风险。

fileContent你有一个 document ,这意味着它是 DOM 节点的集合。您如何使用该文档取决于您加载的内容。呈现节点的一种方法是附加 fileContent.body放到你的本地 DOM 上,像这样:

Polymer.dom(this.root).appendChild(this.fileContent.body);

这是一个更完整的示例 ( http://jsbin.com/rafaso/edit?html,output ):

<content-loader file-path="polymer/bower.json"></content-loader>

<dom-module id="content-loader">

<template>
<pre id="content"></pre>
</template>

<script>

Polymer({
is: "content-loader",
properties: {
filePath: {
type: String,
observer: 'loadFile'
}
},

loadFile: function(path) {
if (this.filePath) {
console.log(this.filePath);
var link = this.importHref(this.filePath,
function() {
Polymer.dom(this.$.content).appendChild(link.import.body);
},
function(){
console.log("error");
}
);
}
}
});

</script>
</dom-module>

关于javascript - 使用 Polymer importHref 动态加载 HTML 页面,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31053947/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com