gpt4 book ai didi

javascript - 为什么一切正常时 importNode 不执行?

转载 作者:太空宇宙 更新时间:2023-11-04 15:28:46 25 4
gpt4 key购买 nike

我想使用 HTML 导入,因此我创建了两个文件。
文件1:

<!DOCTYPE html>
<html>
<head>
<style>
div {
height: 300px;
width: 300px;
background-color: yellow;
}
</style>
</head>
<body>
<div></div>
</body>
</html>

文件2:

<!DOCTYPE html>
<html>
<head>
<link rel='import' href='test.html' id='LINK'>
<script>
var LINK = document.getElementById('LINK');
var test = LINK.import;
var content = document.importNode(test.content, true);
document.body.appendChild(content);

</script>
</head>
<body>
</body>
</html>

当我执行 File2 时,我应该看到一个黄色方 block ,但我却收到此错误:

未捕获类型错误:无法在“文档”上执行“导入节点”:参数 1 不是“节点”类型。
在 Import.html:8

当我将“test”变量记录到控制台时,我得到了包含 File1 的文档,因此一切正常。我只是不明白该错误的含义以及它为什么不起作用。

最佳答案

当你写下:

var content = document.importNode(test.content, true);

...您认为test<template>元素。

因此,在您导入的文档中,您应该有一个 <template>元素。

test.html:

<html>
<head>
<style>
div {
height: 300px;
width: 300px;
background-color: yellow;
}
</style>
</head>
<body>
<template><div></div></template>
</body>
</html>

在主文件中,使用querySelector() (或其他选择器函数)获取模板:

var LINK = document.getElementById('LINK');
var test = LINK.import.querySelector('template');
var content = document.importNode(test.content, true);
...

关于javascript - 为什么一切正常时 importNode 不执行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44990289/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com