我正在尝试使用div的document.getElementById下载自定义元素的div内容,并尝试从JS FIddle实现下载选项 - http://jsfiddle.net/evx9stLb/
从控制台,我得到以下错误
pen.js:6 Uncaught TypeError:无法读取属性&inner;内部HTML'为null
在下载(pen.js:6)
在HTMLButtonElement.onclick(index.html:15)
HTML:
<head>
<base href="https://polygit.org/polymer+v2.0.0/shadycss+webcomponents+1.0.0/components/">
<link rel="import" href="polymer/polymer.html">
<link rel="import" href="iron-collapse/iron-collapse.html">
</head>
<body>
<x-foo></x-foo>
<button onClick="download()">Download</button>
<dom-module id="x-foo">
<template>
<button on-click="toggle">toggle collapse</button>
<div id="content">
<iron-collapse id="collapse">
<div>Content goes here...</div>
</iron-collapse>
</div>
</template>
</dom-module>
</body>
JS:
function download(){
var a = document.body.appendChild(
document.createElement("a")
);
a.download = "export.html";
a.href = "data:text/html," + document.getElementById("content").innerHTML;
a.click();
}
class XFoo extends Polymer.Element {
static get is() { return 'x-foo'; }
static get properties() {
return {};
}
toggle() {
this.$.collapse.toggle();
}
}
customElements.define(XFoo.is, XFoo);
我在下面的代码 - https://codepen.io/nagasai/pen/ZyRKxj
答案 0 :(得分:0)
进行一些更新,并提供帮助,
HTML
<head>
<base href="https://polygit.org/polymer+v2.0.0/shadycss+webcomponents+1.0.0/components/">
<link rel="import" href="polymer/polymer.html">
<link rel="import" href="iron-collapse/iron-collapse.html">
</head>
<body>
<x-foo></x-foo>
<dom-module id="x-foo">
<template>
<button on-click="download">Download</button>
<button on-click="toggle">toggle collapse</button>
<div id="content">
<iron-collapse id="collapse">
<div>Content goes here...</div>
</iron-collapse>
</div>
</template>
</dom-module>
</body>
JS
class XFoo extends Polymer.Element {
static get is() { return 'x-foo'; }
static get properties() {
return {};
}
toggle() {
this.$.collapse.toggle();
}
download(){
var a = document.body.appendChild(
document.createElement("a")
);
a.download = "export.html";
a.href = "data:text/html," + this.$.content.innerHTML;
a.click();
console.log(this.$.content.innerHTML);
}
}
customElements.define(XFoo.is, XFoo);
答案 1 :(得分:0)
文档查询(在光dom上)不会刺穿shadowDom。要做到这一点,你必须专门选择元素并查询它的shadowRoot。
它看起来像这样
a.href = "data:text/html," + document.getElementsByTagName('x-foo')[0].shadowRoot.querySelector('#content').innerHTML;
但是,如果您无法修改元素本身,请执行此操作。在其他人的shadowRoot中骚动是不好的。
如Frank R.所示,它更好地修改元素本身并提供下载功能。
您可以使用类似
之类的外部元素轻松触发此操作document.getElementsByTagName('x-foo')[0].download();
答案 2 :(得分:0)