QuerySelector在HTML导入上找不到模板 [英] QuerySelector not finding template on HTML import

查看:90
本文介绍了QuerySelector在HTML导入上找不到模板的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前正在尝试学习如何使用最新的稳定的Chrome 52(不使用Polymer来使用Web组件)(我也已经在Chrome 52上通过webcomponents.js polyfill尝试了此操作).但是,当我这样做时,querySelector似乎出现错误.当我尝试通过document.querySelector('#template')在控制台中获取(名称很差的模板ID)时,它为null,无法找到它.

I am currently trying to learn how to use web components (without the use of Polymer) using the latest stable Chrome 52 (I have also tried this with the webcomponents.js polyfill on Chrome 52). However, when I do I seem to get an error with the querySelector. When I attempt to grab the (admittedly poorly named template id) in the console via document.querySelector('#template') it is null and is unable to find it.

我正在使用本指南,尽管它带有一些ES6语法. (我也尝试了直接复制和粘贴,但也遇到了同样的问题)

I am using this guide albeit with some ES6 syntax. (I also tried direct copy and paste and it had the same issue)

我也尝试在shadowDOM中搜索,但是那里也不存在.

I also tried to search within the shadowDOM, but it didn't exist there either.

view.html

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

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内的<script>中,请勿使用document.querySelector(...).

In the <script>s inside the imported HTML, don't use 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');

示例(修正了示例中的问题):

Example (fixing the example in the question):

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));
    }
}

兼容性:

IE 11不支持.大多数浏览器(包括Edge)实现,并且对于 IE 10及以下版本,有一个polyfill .

Only IE 11 won't support it. Most browsers (including Edge) implement it, and for IE 10 and below there is a polyfill.

这篇关于QuerySelector在HTML导入上找不到模板的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆