gpt4 book ai didi

javascript - 为什么我的 appendChild 不能与 createDocumentFragment 一起使用?

转载 作者:行者123 更新时间:2023-11-29 21:27:58 26 4
gpt4 key购买 nike

我正在尝试将新创建的元素附加到 div,然后将 div 附加到文档片段,但它没有按预期工作。请帮我确定我缺少的东西。

//array of values to look up
let channels = ["channel1", "channel2", "channel3","channel4","channel5","channel6","channel7","channel8","channel9","channel10","channel11","channel12","channel13","channel14","channel15","channel16"];

//jsonp request function defined
function streamRequest () {

//identify DOM elements for final appendChild
let docFrag = document.createDocumentFragment();
let container = document.getElementById("main-container");

//create container and elements for the acquired information
let div = document.createElement("div");
let image = document.createElement("img");
let p = document.createElement("p");
let p1 = document.createElement("p");
let p2 = document.createElement("p");

//variables for request responses
let logo;
let name;
let status;
let game;

channels.forEach(function channelsRequest(channel){

$.getJSON("https://api.twitch.tv/kraken/streams/" + channel + "?callback=?", function callback(data) {
if(data.stream === null){
status = "Offline"
game = "Offline"
} else if (data.stream != null) {
status = "Online"
game = data.stream.game
}
console.log(channel, status, game);

$.getJSON("https://api.twitch.tv/kraken/channels/" + channel + "?callback=?",function logoRequest(data) {

name = data.display_name;

if(data.logo === null) {
logo = "http://www.logowik.com/uploads/images/379_twitch.jpg"
} else if (data.logo != null) {
logo = data.logo
}

//set attributes and inner HTML for new elements
image.setAttribute("src",logo);
image.setAttribute("alt","photo of channel's image");
image.className = "image";
p.innerHTML = name;
p.className = "name";
p1.innerHTML = status;
p1.className = "status";
p2.innerHTML = game;
p2.className = "game";

//append elements to the div
div.appendChild(image)
div.appendChild(p)
div.appendChild(p1)

if(status === "Online"){
div.appendChild(p2)
}

div.className = "tv-block";
docFrag.appendChild(div);

console.log(data, name, logo, docFrag);
});
});
});
//append final document fragment to the DOM
container.appendChild(docFrag);
};

`

来 self understand ,您应该能够将所有内容附加到 div,然后将 div 附加到片段。当我运行代码时,没有对 DOM 进行任何修改。我觉得可能是作用域问题,或者第二个json请求没有设置好

最佳答案

我知道这个答案会在一年后出现,但由于我刚刚完成了同样的挑战,所以我认为分享我的解决方案可能是有意义的,因为我也遇到了同样的问题。 It looks like创建一个新的 DOM 元素并将所有生成的 div 附加到它,然后将这个元素附加到现有的 DOM 元素比使用文档片段更快。所以我的结构看起来像这样:

<body>
<main>
<header>
</header>
</main>
<footer>
</footer>
</body>

然后我将一个在 js 中创建并包含所有生成的 div 的 div#container 附加到主体。

这是 completed project 的链接.

关于javascript - 为什么我的 appendChild 不能与 createDocumentFragment 一起使用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37065209/

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