在进行API调用并获取所请求的数据后,我正试图在页面上显示它。但是,我知道在vanilla JS中只使用两种方法:一种是innerHTML
,只是将所有代码放在那里,另一种是使用多个object.createElement
调用。
这是我的代码中执行此操作的部分。每次进行API调用并加载响应时都会调用此函数:
function buildLinks() {
spin();
/* Checks if current user [passed as param] is currently live by matching userID's from 'streams' and 'users'
For each user that's live, add a 'name' property to userID_stream with the name of the game being played. */
userID_users.forEach(elem => {
function checkIfLive(user) {
for (let key of userID_streams) {
if (key.user_id == user.id) {
if (key.name == null) {
userGame.textContent = "Not In Game."
return true;
} else {
userGame.textContent = "Game: " + key.name;
return true;
}
}
}
}
const mainDiv = document.createElement('div');
const imgDiv = document.createElement('div');
const textDiv = document.createElement('div');
const userLinkText = document.createElement('p');
const userLinkUrl = document.createElement('a');
const userImg = document.createElement('img');
const userStatus = document.createElement('p');
const userGame = document.createElement('p');
userLinkUrl.href = `https://twitch.tv/${elem.login}`;
userLinkUrl.textContent = `${elem.display_name}`;
userImg.src = `${elem.profile_image_url}`;
if (checkIfLive(elem)) {
userStatus.textContent = 'Live';
userStatus.classList.add('status_live');
} else {
userStatus.textContent = 'Offline';
userStatus.classList.add('status_offline');
}
userLinkText.appendChild(userLinkUrl);
imgDiv.appendChild(userImg);
textDiv.appendChild(userLinkText);
textDiv.appendChild(userStatus);
textDiv.appendChild(userGame);
userLinkText.classList.add('username');
userStatus.classList.add('status');
userGame.classList.add('game');
mainDiv.classList.add('stream');
imgDiv.classList.add('stream_img');
textDiv.classList.add('stream_desc');
mainDiv.appendChild(imgDiv);
mainDiv.appendChild(textDiv);
content.appendChild(mainDiv);
});
}
正如您所看到的,它有很多重复和创建元素,然后添加calsses并将每个创建的元素附加到父元素中。
我的问题是,使用vanilla JS有更好的方法吗?如果是这样,我应该怎么做呢?
答案 0 :(得分:2)
你最终会重新发明轮子,所以只需使用一些有帮助的视图库(除了jQuery,从不使用jQuery)。
你可能会这样写:
const element = (name, ...args) => {
const e = document.createElement(name);
args.forEach(arg => {
if (arg instanceof HTMLElement)
e.appendChild(arg);
else if (typeof arg == 'string')
e.appendChild(document.createTextNode(arg));
else
Object.entries(arg).forEach(([key, value]) => e.setAttribute(key, value));
});
return e;
};
console.log(
element("div", { class: "main" },
element("h1", "Title"),
element("div", { class: "content" },
element("span", "Text Here"),
element("span", "Even More Text Here")
)
).outerHTML
);