簡體   English   中英

使用Javascript循環創建多個HTML元素

[英]Using Javascript loop to create multiple HTML elements

我想使用javascript循環創建多個HTML包裝器元素,並將JSON響應API數據插入到某些元素(圖像,標題,URL等)中。

這是我需要逐行處理的嗎?

<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>

我正在嘗試:

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元素重復該過程。

  • 創建A標簽
  • 為A標簽創建類和href屬性
  • 將類別名稱和網址附加到屬性
  • 在主包裝紙上附加A標簽

  • 創建DIV

  • 為DIV創建類屬性
  • 將DIV附加到新添加的A標簽

如果您能啟發我做我想在這里解釋的最好方法,我將不勝感激。 似乎會變得非常混亂。

這是我的答案。 被注明。 為了查看摘要中的效果,您必須進入開發人員控制台以檢查wrapper元素或查看開發人員控制台日志。

我們基本上創建了一些輔助方法來輕松創建元素並將其附加到DOM-實際上並不像看起來那樣難。 這還應該使您輕松地將JSON檢索的對象作為屬性附加到元素中!

這是一個基本版本,可讓您了解正在發生的事情以及如何使用它

//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> 

這是如何使用更透徹注釋的代碼來具體執行您要求的操作。

//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> 

簡潔版本

Markup.js的循環

長版

你會發現許多對這個問題的解決方案的工作 但這可能不是重點。 關鍵是:對嗎? 而且您可能會使用錯誤的工具來解決該問題。

我使用的代碼做了類似的事情。 我沒有寫它,但是我不得不使用它。 您會發現類似的代碼很快變得很難管理。 您可能會想:“哦,但是我知道應該怎么做。一旦完成,我就不會更改。”

代碼分為兩類:

  • 您停止使用的代碼,因此無需更改。
  • 您一直使用的代碼,因此需要進行更改。

所以,“行得通嗎?” 這不是正確的問題。 有很多問題,但是有些問題是:“我能維持這一點嗎?它易於閱讀嗎?如果我更改了一個部分,它只會更改我需要更改的部分,還是會更改我的其他內容?不是要改變嗎?”

我要說的是,您應該使用模板庫。 JavaScript有很多。

通常,您應該使用整個JavaScript應用程序框架。 如今主要有三個:

  • ReactJS
  • Vue.js
  • 角度2

為了誠實起見,請注意,我沒有遵循自己的建議,仍然使用Angular。 (原始的不是Angular2。)但這是一個陡峭的學習曲線。 有很多庫還包含模板功能。

但是顯然您已經設置了一個完整的項目,並且只想將模板插入現有的 JavaScript代碼中。 您可能希望使用一種模板語言來完成其工作並避免礙事。 當我開始的時候,我也想要那個。 我使用了Markup.js。 它很小,很簡單,可以完成您在這篇文章中想要的。

https://github.com/adammark/Markup.js/

這是第一步。 我認為您需要它的循環功能 從此開始,並按時完成整個框架。

看看這個-[underscore._template]它很小,在這種情況下很有用。 https://www.npmjs.com/package/underscore.template )。

 const targetElement = document.querySelector('#target') // Define your template const template = UnderscoreTemplate( '<a class="<%- link.className %>" href="<%- link.url %>">\\ <div class="<%- wrapper.className %>">\\ <div class="<%- thumbnail.className %>">\\ <img src="<%- thumbnail.image %>">\\ </div>\\ <div class="<%- info.className %>">\\ <div class="<%- info.title.className %>"><%- info.title.text %></div>\\ </div>\\ </div>\\ </a>'); // Define values for template const obj = { link: { className: 'scoreboard-video-outer-link', url: '#someurl' }, wrapper: { className: 'scoreboard-video--wrapper' }, thumbnail: { className: 'scoreboard-video--thumbnail', image: 'http://via.placeholder.com/350x150' }, info: { className: 'scoreboard-video--info', title: { className: 'scoreboard-video--title', text: 'Pelicans @ Bulls Postgame: E`Twaun Moore 10-8-17' } } }; // Build template, and set innerHTML to output element. targetElement.innerHTML = template(obj) // And of course you can go into forEach loop here like const arr = [obj, obj, obj]; // Create array from our object arr.forEach(item => targetElement.innerHTML += template(item)) 
 <script src="https://unpkg.com/underscore.template@0.1.7/dist/underscore.template.js"></script> <div id="target">qq</div> 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM