我目前正在尝试使用最新的稳定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)