gpt4 book ai didi

JavaScript - 使用克隆节点和 Json 数据克隆模板

转载 作者:行者123 更新时间:2023-12-03 02:32:21 26 4
gpt4 key购买 nike

我想使用 JSON 数据和模板创建多个元素,方法是创建模板的克隆并将它们附加到特定的 div。

但是,当使用克隆的模板变量时,克隆不能在处理 JSON 数据的函数内部使用,即使该克隆位于函数之上(这应该使其对于同一级别的所有内容都是全局的?)。

HTML

<template class="content">
<h2>Hello World</h2>
<h3>Hello World</h3>
</template>

<div class="box">

</div>

JS

let content = document.querySelector(".content").content;
let box = document.querySelector(".box");

doStuff();

function doStuff() {
let content = document.querySelector(".content").content;
let box = document.querySelector(".box");
//make a clone of the template
let clone = content.cloneNode(true);

// change content of H2
clone.querySelector("h2").textContent = "First Box";

// change content of H3 with data fetched from API
fetch("http://kea-alt-del.dk/t5/api/product?id=21").then(e => e.json()).then(productJson => otherStuff(productJson));

function otherStuff(productJson) {
clone.querySelector("h3").textContent = productJson.name;

}

// add the clone to the box div
box.appendChild(clone);

}

以工作 fiddle 为例:https://jsfiddle.net/c1x98hmh/4/从结果中我们可以看到h2内容发生了变化,但是h3内容保持不变。控制台日志告诉我克隆为空。

当我们将模板元素更改为 div 时,这个示例如何起作用?(我需要这个 Json,这就是为什么我有模板、函数、克隆和内部函数)

最佳答案

clone 是一个 DocumentFragment 对象。 Here's what appendChild does with a DocumentFragment :

If the given child is a DocumentFragment, the entire contents of the DocumentFragment are moved into the child list of the specified parent node.

关键字被“移动”——这就是为什么在调用 otherStuffclone 为空的原因。

关于JavaScript - 使用克隆节点和 Json 数据克隆模板,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48682337/

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