使用 Javascript 循环创建多个 HTML 元素 [英] Using Javascript loop to create multiple HTML elements

查看:35
本文介绍了使用 Javascript 循环创建多个 HTML 元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用 javascript 循环来创建多个 HTML 包装元素并将 JSON 响应 API 数据插入到某些元素(图像、标题、网址等...)中.

这是我需要逐行处理的吗?

<div class="scoreboard-video--wrapper"><div class="scoreboard-video--thumbnail"><img src="http://via.placeholder.com/350x150">

<div class="scoreboard-video--info"><div class="scoreboard-video--title">鹈鹕@公牛赛后:E'Twaun Moore 10-8-17</div>

</a>

我正在尝试什么:

var link = document.createElement('a');document.getElementsByTagName("a")[0].setAttribute("class", "scoreboard-video-outer-link");document.getElementsByTagName("a")[0].setAttribute("url", "google.com");mainWrapper.appendChild(link);var videoWrapper= document.createElement('div');document.getElementsByTagName("div")[0].setAttribute("class", "scoreboard-video-outer-link");link.appendChild(videoWrapper);var videoThumbnailWrapper = document.createElement('div');document.getElementsByTagName("div")[0].setAttribute("class", "scoreboard-video--thumbnail");videoWrapper.appendChild(videoThumbnailWrapper);var videoImage = document.createElement('img');document.getElementsByTagName("img")[0].setAttribute("src", "url-of-image-from-api");videoThumbnailWrapper.appendChild(videoImage);

然后我基本上对所有嵌套的 HTML 元素重复该过程.

如果您能以最佳方式启发我,我将不胜感激?好像会变得很乱.

这是我的答案.已注明.为了查看代码段中的效果,您必须进入开发人员控制台以检查包装器元素或查看开发人员控制台日志.

我们基本上创建了一些辅助方法来轻松创建元素并将它们附加到 DOM - 这真的没有看起来那么难.这也应该让您能够轻松地将 JSON 检索到的对象作为属性附加到您的元素!

这是一个基本版本,可让您了解正在发生的事情以及如何使用它

//创建元素函数功能创建(标签名称,道具){return Object.assign(document.createElement(tagName), (props || {}));}//附加子函数函数 ac(p, c) {如果 (c) p.appendChild(c);返回 p;}//例子://获取包装div让 mainWrapper = document.getElementById("mainWrapper");//创建链接和divlet link = create("a", { href:"google.com" });让 div = create("div", { id: "myDiv" });//将链接作为子节点添加到div,将结果添加到mainWrapperac(mainWrapper, ac(div, 链接));

以下是如何使用更完整的标记代码来具体完成您所要求的操作.

//获取主包装器让 mainWrapper = document.getElementById("mainWrapper");//制作一个函数来轻松创建元素//函数接受一个 tagName 和一个可选的属性值对象//使用 Object.assign 我们可以快速制作定制元素.功能创建(标签名称,道具){return Object.assign(document.createElement(tagName), (props || {}));}//document.appendChild 很棒,除了//它不提供简单的可堆叠性//这样做的原因是它总是返回附加的子元素//我们创建一个从父级附加到子级的函数//并返回编译后的元素(父级).//因为我们总是返回父级(无论是否指定了子级)//我们可以递归调用这个函数,效果很好//(你会在下面看到这个)函数 ac(p, c) {如果 (c) p.appendChild(c);返回 p;}//这些是你想要追加的元素//注意制作它们是多么容易!//直接向 HTMLElement 添加类时仅供参考//要赋值的属性是className——不是class//这是一个常见的错误,所以没什么大不了的!var link = create("a", {className: "记分板视频外链",网址:google.com"});var videoWrapper = create("div", {className:记分板视频外部链接"});var videoThumbnailWrapper = create("div", {className: "记分板-视频--缩略图"});var videoImage = create("img", {src: "来自 api 的图像 url"});//这里是递归的地方:ac(mainWrapper, ac(link, ac(videoWrapper, ac(videoThumbnailWrapper, videoImage))));//请记住,向后读取 ac 函数可能是最容易的//逻辑是这样的://将 videoImage 附加到 videoThumbnailWrapper//附加(videoImage+videoThumbnailWrapper)到videoWrapper//附加(videoWrapper+videoImage+videoThumbnailWrapper)到链接//附加(link+videoWrapper+videoImage+videoThumbnailWrapper)到mainWrapper

I would like to use a javascript loop to create multiple HTML wrapper elements and insert JSON response API data into some of the elements (image, title, url, etc...).

Is this something I need to go line-by-line with?

<a class="scoreboard-video-outer-link" href="">
  <div class="scoreboard-video--wrapper">
    <div class="scoreboard-video--thumbnail">
      <img src="http://via.placeholder.com/350x150">
    </div>
    <div class="scoreboard-video--info">
      <div class="scoreboard-video--title">Pelicans @ Bulls Postgame: E'Twaun Moore 10-8-17</div>
    </div>
  </div>
</a>

What I am trying:

var link = document.createElement('a');
document.getElementsByTagName("a")[0].setAttribute("class", "scoreboard-video-outer-link");
document.getElementsByTagName("a")[0].setAttribute("url", "google.com"); 
mainWrapper.appendChild(link);

var videoWrapper= document.createElement('div');
document.getElementsByTagName("div")[0].setAttribute("class", "scoreboard-video-outer-link");
link.appendChild(videoWrapper);

var videoThumbnailWrapper = document.createElement('div');
document.getElementsByTagName("div")[0].setAttribute("class", "scoreboard-video--thumbnail");
 videoWrapper.appendChild(videoThumbnailWrapper);

var videoImage = document.createElement('img');
document.getElementsByTagName("img")[0].setAttribute("src", "url-of-image-from-api");
videoThumbnailWrapper.appendChild(videoImage);

Then I basically repeat that process for all nested HTML elements.

  • Create A-tag
  • Create class and href attributes for A-tag
  • Append class name and url to attributes
  • Append A-tag to main wrapper

  • Create DIV

  • Create class attributes for DIV
  • Append DIV to newly appended A-tag

I'd greatly appreciate it if you could enlighten me on the best way to do what I'm trying to explain here? Seems like it would get very messy.

解决方案

Here's my answer. It's notated. In order to see the effects in the snippet you'll have to go into your developers console to either inspect the wrapper element or look at your developers console log.

We basically create some helper methods to easily create elements and append them to the DOM - it's really not as hard as it seems. This should also leave you in an easy place to append JSON retrieved Objects as properties to your elements!

Here's a Basic Version to give you the gist of what's happening and how to use it

//create element function

function create(tagName, props) {
  return Object.assign(document.createElement(tagName), (props || {}));
}

//append child function

function ac(p, c) {
  if (c) p.appendChild(c);
  return p;
}

//example: 
//get wrapper div
let mainWrapper = document.getElementById("mainWrapper");

//create link and div
let link = create("a", { href:"google.com" });
let div = create("div", { id: "myDiv" });

//add link as a child to div, add the result to mainWrapper
ac(mainWrapper, ac(div, link));

//create element function

function create(tagName, props) {
  return Object.assign(document.createElement(tagName), (props || {}));
}

//append child function

function ac(p, c) {
  if (c) p.appendChild(c);
  return p;
}

//example: 
//get wrapper div
let mainWrapper = document.getElementById("mainWrapper");

//create link and div
let link = create("a", { href:"google.com", textContent: "this text is a Link in the div" });
let div = create("div", { id: "myDiv", textContent: "this text is in the div! " });

//add link as a child to div, add the result to mainWrapper
ac(mainWrapper, ac(div, link));

div {
border: 3px solid black;
padding: 5px;

}

<div id="mainWrapper"></div>

Here is how to do specifically what you asked with more thoroughly notated code.

//get main wrapper
let mainWrapper = document.getElementById("mainWrapper");

//make a function to easily create elements
//function takes a tagName and an optional object for property values
//using Object.assign we can make tailored elements quickly.

function create(tagName, props) {
  return Object.assign(document.createElement(tagName), (props || {}));
}


//document.appendChild is great except 
//it doesn't offer easy stackability
//The reason for this is that it always returns the appended child element
//we create a function that appends from Parent to Child 
//and returns the compiled element(The Parent).
//Since we are ALWAYS returning the parent(regardles of if the child is specified) 
//we can recursively call this function to great effect
//(you'll see this further down)
function ac(p, c) {
  if (c) p.appendChild(c);
  return p;
}

//these are the elements you wanted to append
//notice how easy it is to make them!

//FYI when adding classes directly to an HTMLElement
//the property to assign a value to is className  -- NOT class
//this is a common mistake, so no big deal!

var link = create("a", {
  className: "scoreboard-video-outer-link",
  url: "google.com"
});

var videoWrapper = create("div", {
  className: "scoreboard-video-outer-link"
});

var videoThumbnailWrapper = create("div", {
  className: "scoreboard-video--thumbnail"
});

var videoImage = create("img", {
  src: "url-of-image-from-api"
});

//here's where the recursion comes in:
ac(mainWrapper, ac(link, ac(videoWrapper, ac(videoThumbnailWrapper, videoImage))));

//keep in mind that it might be easiest to read the ac functions backwards
//the logic is this:

//Append videoImage to videoThumbnailWrapper
//Append (videoImage+videoThumbnailWrapper) to videoWrapper 
//Append (videoWrapper+videoImage+videoThumbnailWrapper) to link
//Append (link+videoWrapper+videoImage+videoThumbnailWrapper) to mainWrapper

let mainWrapper = document.getElementById('mainWrapper');

function create(tagName, props) {
  return Object.assign(document.createElement(tagName), (props || {}));
}

function ac(p, c) {
  if (c) p.appendChild(c);
  return p;
}

var link = create("a", {
  className: "scoreboard-video-outer-link",
  url: "google.com"
});

var videoWrapper = create("div", {
  className: "scoreboard-video-outer-link"
});

var videoThumbnailWrapper = create("div", {
  className: "scoreboard-video--thumbnail"
});



var videoImage = create("img", {
  src: "url-of-image-from-api"
});

ac(mainWrapper, ac(link, ac(videoWrapper, ac(videoThumbnailWrapper, videoImage))));
//pretty fancy.
//This is just to show the output in the log,
//feel free to just open up the developer console and look at the mainWrapper element.

console.dir(mainWrapper);

<div id="mainWrapper"></div>

这篇关于使用 Javascript 循环创建多个 HTML 元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
前端开发最新文章
热门教程
热门工具
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆