简体   繁体   English

使用 JavaScript 动态生成 HTML 元素列表的最佳方法是什么?

[英]What is the best way to generate a list of HTML elements dynamically using JavaScript?

A lot of important web sites like Amazon, Facebook, Twitter... essentially consist of a list HTML elements being divs or others that are generated dynamically from a search query or from a menu selection.许多重要的网站,如亚马逊、Facebook、Twitter...基本上由一个列表 HTML 元素组成,这些元素是div或从搜索查询或菜单选择动态生成的其他元素。 For example:例如:

  • Amazon : a list of products亚马逊:产品清单
  • Facebook : a list of posts Facebook :帖子列表
  • Twitter : a list of twitters推特推特列表

What is the best way to generate such lists according to the criteria mentioned using only JavaScript?根据仅使用 JavaScript 提到的标准生成此类列表的最佳方法是什么?

Facebook for example use React to generate dynamic content on the client side.例如,Facebook 使用 React 在客户端生成动态内容。 It's a good library ( framework) for that kind of things... but im gonna answer your question.对于这类事情,这是一个很好的库(框架)......但我会回答你的问题。 I guess that's the correct way to deal with dynamic content on javascript "by hand", just javascript.我想这是“手动”处理javascript动态内容的正确方法,只是javascript。

From the W3Schools.来自 W3Schools。

var fruits = ["apple", "orange", "cherry"]; varfruits = ["apple", "orange", "cherry"]; fruits.forEach(myFunction);水果.forEach(myFunction);

//HTML //HTML

function myFunction(item, index) { document.getElementById("demo").innerHTML += index + ":" + item + " function myFunction(item, index) { document.getElementById("demo").innerHTML += index + ":" + item + "
"; } "; }

that's the approach used for dynamic content.这就是用于动态内容的方法。 Here's the proper answer to your question How to create list in HTML dynamically?这是您的问题如何动态创建 HTML 列表的正确答案

To do this with vanilla JavaScript, you want to start with an array of stuff to be displayed, then iterate over the list and call document.createElement for each item.要使用 vanilla JavaScript 执行此操作,您需要从要显示的内容数组开始,然后遍历列表并为每个项目调用 document.createElement。 There are many ways to implement this.有很多方法可以实现这一点。 One example would look something like this:一个例子看起来像这样:

const testStuff = [ 'product 1', 'product 2', 'product 3' ]

for (let i = 0; i < testStuff.length; i++) {
  let element = document.createElement('div');
  element.innerHTML = testStuff[i];
  document.getElementsByTagName('body')[0].appendChild(element);
}

This would result in 3 divs in the body of the HTML document with each of the values from the array.这将导致 HTML 文档正文中有 3 个 div,其中包含数组中的每个值。 It is worth pointing out that all of the companies that you listed above are definitely using ES6 syntax and JavaScript frameworks to make this whole thing easier.值得指出的是,您上面列出的所有公司肯定都在使用 ES6 语法和 JavaScript 框架来简化这一切。

Hope that helps!希望有帮助!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM