Aly*_*zog 6 html javascript google-chrome web-component
我目前正在尝试使用最新的稳定Chrome 52来学习如何使用Web组件(不使用Polymer)(我还尝试使用Chrome 52上的webcomponents.js polyfill).但是,当我这样做时,我似乎得到querySelector的错误.当我试图在控制台中获取(document.querySelector('#template')通常名称命名很差的模板ID)时,它是null并且无法找到它.
我正在使用本指南,尽管有一些ES6语法.(我也试过直接复制和粘贴,它有同样的问题)
我也尝试在shadowDOM中搜索,但它也不存在.
view.html
<template id="template">
<style>
</style>
<div class="container">
<h1>WZView</h1>
</div>
</template>
<script>
"use strict";
class WZView extends HTMLElement {
createdCallback () {
var root = this.createShadowRoot();
var template = document.querySelector('#template');
root.appendChild(document.importNode(template.content, true));
}
}
document.registerElement('wz-view', WZView);
</script>
Run Code Online (Sandbox Code Playgroud)
的index.html
<!DOCTYPE html>
<html>
<head>
<!--<script src="/bower_components/webcomponentsjs/webcomponents.js"></script>-->
<link rel="import" href="view.html">
</head>
<body>
<wz-view></wz-view>
</body>
</html>
Run Code Online (Sandbox Code Playgroud)
安慰:
view.html:16 Uncaught TypeError: Cannot read property 'content' of null
> document.querySelector('#template')
null
Run Code Online (Sandbox Code Playgroud)
在<script>导入的 HTML 内的 s 中,请勿使用document.querySelector(...).
// while inside the imported HTML, `currentDocument` should be used instead of `document`
var currentDocument = document.currentScript.ownerDocument;
...
// notice the usage of `currentDocument`
var templateInsideImportedHtml = currentDocument.querySelector('#template');
Run Code Online (Sandbox Code Playgroud)
示例(修复问题中的示例):
var currentDocument = document.currentScript.ownerDocument; // <-- added this line
class WZView extends HTMLElement {
createdCallback () {
var root = this.createShadowRoot();
var template = currentDocument.querySelector('#template'); // <-- changed this line
root.appendChild(document.importNode(template.content, true));
}
}
Run Code Online (Sandbox Code Playgroud)
兼容性:
只有IE 11 不支持。大多数浏览器(包括 Edge)都实现了它,并且对于IE 10 及更低版本,有一个 polyfill。