【发布时间】:2016-06-06 19:10:03
【问题描述】:
我目前正在尝试学习如何使用最新的稳定版 Chrome 52 使用 Web 组件(不使用 Polymer)(我也尝试过使用 Chrome 52 上的 webcomponents.js polyfill)。但是,当我这样做时,我似乎收到了 querySelector 错误。当我尝试通过document.querySelector('#template') 在控制台中获取(诚然命名不佳的模板 ID)时,它为空并且无法找到它。
我正在使用this guide,尽管使用了一些 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>
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>
控制台:
view.html:16 Uncaught TypeError: Cannot read property 'content' of null
> document.querySelector('#template')
null
【问题讨论】:
-
也许 不是有效的 html 标签?
-
感谢艾莉莎。学到了一些新东西 :) 如果你使用 document.querySelectorAll('#template') 你的代码能工作吗?
-
和以前一样的错误
-
如果我在普通网页中创建模板元素,可以使用querySelector来获取元素。您的模板元素在文档对象中不存在,因为它在导入中。试试
document.currentScript.ownerDocument.querySelector('#template')。
标签: javascript html google-chrome web-component