1
我正在創建簡單的自定義元素,我想將其從分隔文件中導入。當它在同一個文件t
給予正確的html元素,但是當它在外部文件中時,它是undefined
。這裏是我的index.html
文件:在導入的文件中無法通過標識找到模板
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<link rel="import" href="example-container.html">
</head>
<body>
<example-container></example-container>
</body>
</html>
而且example-container.html
:
<template id="example-container">
<style>
</style>
</template>
<script>
// Make sure you extend an existing HTMLElement prototype
var ExampleContainerProto = Object.create(HTMLElement.prototype);
//var t = document.querySelector('#example-container');
// Setup optional lifecycle callbacks
ExampleContainerProto.createdCallback = function() {
var t = document.querySelector('#example-container');
console.log(t);
};
var ExampleContainer = document.registerElement('example-container', {prototype: ExampleContainerProto});
</script>
我的另一種方法是在全球範圍內定義t
,像這樣:
var t = document.querySelector('#wizard-container');
WizardContainerProto.createdCallback = function() {
console.log(t);
...
而且它工作的罰款,但我不想在全球範圍內留下垃圾。
我已經將'var t = ...'行更改爲'var t = document.currentScript.ownerDocument.querySelector('#wizard-container');'現在我有'Uncaught TypeError:無法讀取property' ownerDocument'null' –
@Scimonster As @PiotrŁużecki說,這似乎不起作用:'document === document.currentScript.ownerDocument' – SwiftsNamesake