在 Java 脚本中动态生成嵌套 DIV-结构的有效方法
Efficient ways to dynamiclly generate nested DIV-structures in Java Script
我创建了一个简单的程序,它从数据库中获取数据并以 Instagram post 方式显示。到目前为止一切正常,但我希望找到一种更紧凑的方法来生成这种类型的结构。我正在使用 document.createElement() 方法来完成这项工作,但是 代码非常重复。是否有其他更受欢迎的方法来实现此目的?
Div structure
我的代码使用 document.createElement();
//create post wrapper
newPostWrapper = document.createElement("div");
newPostWrapper.className = "postWrapper";
imageContainer.appendChild(newPostWrapper);
//create image imageamountWRAPPER
newImageAmountWrapper = document.createElement("div");
newImageAmountWrapper.className = "imageamountWRAPPER";
newPostWrapper.appendChild(newImageAmountWrapper);
//create image count
newImageCount = document.createElement("div");
newImageCount.className = "imageamountCOUNT";
newImageCount.innerHTML = "1/2";
newImageAmountWrapper.appendChild(newImageCount);
//create detailsWrapper
newDetailsWrapper = document.createElement("div");
newDetailsWrapper.className = "imageDETAILSWRAPPER";
newPostWrapper.appendChild(newDetailsWrapper);
//createDATEwrapper
newDateWrapper = document.createElement("div");
newDateWrapper.className = "imagedisplayDATEWRAPPER";
newDetailsWrapper.appendChild(newDateWrapper);
//create date
newDate = document.createElement("p");
newDate.className = "imagedisplayDATE";
newDate.innerHTML = imageDate;
newDateWrapper.appendChild(newDate);
//create image wrapper
newImageWrapper = document.createElement("div");
newImageWrapper.className = "imagedisplayWRAPPER";
newImageWrapper.id = "imageWrapper" + i;
newDetailsWrapper.appendChild(newImageWrapper);
//create image
newImage = document.createElement("img");
newImage.className = "imagedisplayIMAGE";
newImage.src = "../../uploads/" + profileContent[i][0];
newImage.id = "img" + i;
newImage.setAttribute('contentID', profileContent[i][1]);
newImageWrapper.appendChild(newImage);
//create descriptionWRAPPER
newDescriptionWrapper = document.createElement("div");
newDescriptionWrapper.className = "descriptionWRAPPER";
newPostWrapper.appendChild(newDescriptionWrapper);
//add description
newDescription = document.createElement("p");
newDescription.className = "description";
newDescription.innerHTML = "A new image for the best community ever!"
newDescriptionWrapper.appendChild(newDescription);
提前致谢
我个人认为基于 : The Content Template element or use Template literals (Template strings) 来扩展和修改解决方案以创建接口更容易。使用 DOM API 来创建和操作节点通常是非常冗长和重复的,例如现在我正在尝试创建一个例子,你使用和模板字符串,但因为你没有显示生成 div 的数据,我必须查看您显示的代码才能知道界面是如何构建的,而且速度很慢。另一方面,如果您使用我列出的解决方案之一,我会更快地知道哪个元素是另一个元素的子元素。
正在做例子,希望稍后更新
我建议使用任何模板机制。有很多 JS 模板引擎,例如 Angular、React 或 Vue。如果你只想使用纯 JS 来做,那么这里是一个可以在循环内完成的例子,
let imageDate = '2020-07-01';
let imgSrc = 'https://live.staticflickr.com/4561/38054606355_26429c884f_b.jpg';
let i = 4; // get it from the loop.
let myContentID = 1234;
let markup = `
<div class="imageContainer">
<div class="postWrapper">
<div class="imageamountWRAPPER">
<div class="imageamountCOUNT">1/2</div>
</div>
<div class="imageDETAILSWRAPPER">
<div class="imagedisplayDATEWRAPPER">
<div class="imagedisplayDATE">${imageDate}</div>
<div class="imagedisplayWRAPPER" id="imageWrapper${i}">
<img id="img${i}" contentID="${myContentID}" class="imagedisplayIMAGE" src="${imgSrc}" alt="">
</div>
</div>
</div>
<div class="descriptionWRAPPER">
<p class="description">A new image for the best community ever!</p>
</div>
</div>
</div>
`;
document.body.innerHTML = markup;
您基本上可以选择使用 .innerHTML
并将整个内容分配为 HTML,或者对每个元素使用 createElement
方法。
在第一种情况下,您可以使用带有模板文字的字符串连接或插值来构建您的字符串。缺点是标记中的错误可能不会立即浮出水面。
如果您更喜欢其他方法,那么您可以选择 jQuery 及其通用的 $
函数和 append
方法。如果没有,你可以抛出你自己的效用函数。
这是一个用于创建 DOM 元素的通用函数:
function elem(tagAndClasses, attribs={}, content=[]) {
if (Array.isArray(attribs) || typeof attribs == "string") { // attribs was omited as argument
content = attribs;
attribs = {};
}
let [tag, ...classes] = tagAndClasses.split(".");
let elem = document.createElement(tag);
elem.className = classes.join(" ");
Object.entries(attribs).forEach(([key, value]) => elem.setAttribute(key, value));
if (Array.isArray(content)) {
for (let child of content) elem.appendChild(child);
} else {
elem.textContent = content;
}
return elem;
}
为您的示例调用它如下:
imageContainer.appendChild(
elem("div.postWrapper", [
elem("div.imageamountWRAPPER" , [
elem("div.imageamountCOUNT", "1/2")
]),
elem("div.imageDETAILSWRAPPER", [
elem("div.imagedisplayDATEWRAPPER", [
elem("p.imagedisplayDATE", imageDate)
]),
elem("div.imagedisplayWRAPPER", { id: "imageWrapper" + i }, [
elem("img.imagedisplayIMAGE", {
src: "../../uploads/" + profileContent[i][0],
id: "img" + i,
contentID: profileContent[i][1]
})
])
]),
elem("div.descriptionWRAPPER", [
elem("p.description", "A new image for the best community ever!")
])
])
);
我创建了一个简单的程序,它从数据库中获取数据并以 Instagram post 方式显示。到目前为止一切正常,但我希望找到一种更紧凑的方法来生成这种类型的结构。我正在使用 document.createElement() 方法来完成这项工作,但是 代码非常重复。是否有其他更受欢迎的方法来实现此目的?
Div structure
我的代码使用 document.createElement();
//create post wrapper
newPostWrapper = document.createElement("div");
newPostWrapper.className = "postWrapper";
imageContainer.appendChild(newPostWrapper);
//create image imageamountWRAPPER
newImageAmountWrapper = document.createElement("div");
newImageAmountWrapper.className = "imageamountWRAPPER";
newPostWrapper.appendChild(newImageAmountWrapper);
//create image count
newImageCount = document.createElement("div");
newImageCount.className = "imageamountCOUNT";
newImageCount.innerHTML = "1/2";
newImageAmountWrapper.appendChild(newImageCount);
//create detailsWrapper
newDetailsWrapper = document.createElement("div");
newDetailsWrapper.className = "imageDETAILSWRAPPER";
newPostWrapper.appendChild(newDetailsWrapper);
//createDATEwrapper
newDateWrapper = document.createElement("div");
newDateWrapper.className = "imagedisplayDATEWRAPPER";
newDetailsWrapper.appendChild(newDateWrapper);
//create date
newDate = document.createElement("p");
newDate.className = "imagedisplayDATE";
newDate.innerHTML = imageDate;
newDateWrapper.appendChild(newDate);
//create image wrapper
newImageWrapper = document.createElement("div");
newImageWrapper.className = "imagedisplayWRAPPER";
newImageWrapper.id = "imageWrapper" + i;
newDetailsWrapper.appendChild(newImageWrapper);
//create image
newImage = document.createElement("img");
newImage.className = "imagedisplayIMAGE";
newImage.src = "../../uploads/" + profileContent[i][0];
newImage.id = "img" + i;
newImage.setAttribute('contentID', profileContent[i][1]);
newImageWrapper.appendChild(newImage);
//create descriptionWRAPPER
newDescriptionWrapper = document.createElement("div");
newDescriptionWrapper.className = "descriptionWRAPPER";
newPostWrapper.appendChild(newDescriptionWrapper);
//add description
newDescription = document.createElement("p");
newDescription.className = "description";
newDescription.innerHTML = "A new image for the best community ever!"
newDescriptionWrapper.appendChild(newDescription);
提前致谢
我个人认为基于 : The Content Template element or use Template literals (Template strings) 来扩展和修改解决方案以创建接口更容易。使用 DOM API 来创建和操作节点通常是非常冗长和重复的,例如现在我正在尝试创建一个例子,你使用和模板字符串,但因为你没有显示生成 div 的数据,我必须查看您显示的代码才能知道界面是如何构建的,而且速度很慢。另一方面,如果您使用我列出的解决方案之一,我会更快地知道哪个元素是另一个元素的子元素。
正在做例子,希望稍后更新
我建议使用任何模板机制。有很多 JS 模板引擎,例如 Angular、React 或 Vue。如果你只想使用纯 JS 来做,那么这里是一个可以在循环内完成的例子,
let imageDate = '2020-07-01';
let imgSrc = 'https://live.staticflickr.com/4561/38054606355_26429c884f_b.jpg';
let i = 4; // get it from the loop.
let myContentID = 1234;
let markup = `
<div class="imageContainer">
<div class="postWrapper">
<div class="imageamountWRAPPER">
<div class="imageamountCOUNT">1/2</div>
</div>
<div class="imageDETAILSWRAPPER">
<div class="imagedisplayDATEWRAPPER">
<div class="imagedisplayDATE">${imageDate}</div>
<div class="imagedisplayWRAPPER" id="imageWrapper${i}">
<img id="img${i}" contentID="${myContentID}" class="imagedisplayIMAGE" src="${imgSrc}" alt="">
</div>
</div>
</div>
<div class="descriptionWRAPPER">
<p class="description">A new image for the best community ever!</p>
</div>
</div>
</div>
`;
document.body.innerHTML = markup;
您基本上可以选择使用 .innerHTML
并将整个内容分配为 HTML,或者对每个元素使用 createElement
方法。
在第一种情况下,您可以使用带有模板文字的字符串连接或插值来构建您的字符串。缺点是标记中的错误可能不会立即浮出水面。
如果您更喜欢其他方法,那么您可以选择 jQuery 及其通用的 $
函数和 append
方法。如果没有,你可以抛出你自己的效用函数。
这是一个用于创建 DOM 元素的通用函数:
function elem(tagAndClasses, attribs={}, content=[]) {
if (Array.isArray(attribs) || typeof attribs == "string") { // attribs was omited as argument
content = attribs;
attribs = {};
}
let [tag, ...classes] = tagAndClasses.split(".");
let elem = document.createElement(tag);
elem.className = classes.join(" ");
Object.entries(attribs).forEach(([key, value]) => elem.setAttribute(key, value));
if (Array.isArray(content)) {
for (let child of content) elem.appendChild(child);
} else {
elem.textContent = content;
}
return elem;
}
为您的示例调用它如下:
imageContainer.appendChild(
elem("div.postWrapper", [
elem("div.imageamountWRAPPER" , [
elem("div.imageamountCOUNT", "1/2")
]),
elem("div.imageDETAILSWRAPPER", [
elem("div.imagedisplayDATEWRAPPER", [
elem("p.imagedisplayDATE", imageDate)
]),
elem("div.imagedisplayWRAPPER", { id: "imageWrapper" + i }, [
elem("img.imagedisplayIMAGE", {
src: "../../uploads/" + profileContent[i][0],
id: "img" + i,
contentID: profileContent[i][1]
})
])
]),
elem("div.descriptionWRAPPER", [
elem("p.description", "A new image for the best community ever!")
])
])
);