我想创建一个自定义元素,它将在html导入时自行注册。
定制element.html:
<html>
<...>
<body>
<template id="myTemplate">
</template>
</body>
<script src="my-script.js">
</html>
MY-的script.js:
let customElementPrototype = Object.create(HTMLElement.prototype);
customElementPrototype.createdCallback = function () {
// somewhere here i want to access <template> to insert it in element
// I've tried document.querySelector("#myTemplate") and
// document.currentScript.ownerDocument.querySelector.querySelector("#myTemplate")
// they don't work either, result of querySelector is null
}
document.registerElement("custom-element", customElementPrototype);
用法:
<html>
<head>
<link rel="import" href="custom-element.html">
</head>
<...>
答案 0 :(得分:4)
在createdCallback
上下方是custom-element
,而不是ownerDocument.
您可以在console.log(this);
内createdCallback
看到这个日志(来自我的{ {3}}):
<div is="custom-element">
</div>
在my-script.js
中,您可以捕获对ownerDocument
的引用,并在回调中使用它。这将允许您的custom元素访问它自己的DOM和导入的HTML的DOM。 e.g。
var mainDoc = document.currentScript.ownerDocument;
完整my-script.js
(我的傻瓜中的script.js
):
var mainDoc = document.currentScript.ownerDocument;
var CustomElementPrototype = Object.create(HTMLElement.prototype);
CustomElementPrototype.createdCallback = function () {
console.log(this); //the div
//import the contents of the template
var clone = document.importNode(mainDoc.querySelector('#myTemplate').content, true);
//append template to div
this.appendChild(clone);
};
document.registerElement("custom-element", {
prototype: CustomElementPrototype,
extends: 'div'
});
与具有某些默认值的模板相结合(此文档可通过mainDoc
获得):
<html>
<body>
<script src="script.js"></script>
<template id="myTemplate">
hello world
<br>
from template
</template>
</body>
</html>
并将HTML全部拉入并使用它:
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="style.css">
<link rel="import" href="custom-element.html">
</head>
<body>
<h1>Hello Plunker!</h1>
<div is="custom-element"></div>
</body>
</html>
这是一个有用的参考: https://plnkr.co/edit/jO3ci8vLxolHhvtGxJQ5