我正在尝试将新创建的元素附加到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);
};
`
从我understand开始,您应该能够将所有内容追加到div中,然后将div附加到片段中。当我运行代码时,没有任何内容被修改为DOM。我认为可能是因为范围界定,或者第二个json请求未正确设置
答案 0 :(得分:2)
我知道这个答案是在一年之后发生的,但是当我刚刚完成同样的挑战时,我认为分享我的解决方案可能是有意义的,因为我也遇到了同样的问题。 It looks like创建一个新的DOM元素并将所有生成的div附加到它,然后将该元素附加到现有的DOM元素比使用文档片段更快。所以我的结构看起来像这样:
<body>
<main>
<header>
</header>
</main>
<footer>
</footer>
</body>
然后我将主要的一个div#容器附加到js并包含所有生成的div。
以下是completed project的链接。