用普通的旧JS动态呈现DOM元素的好方法是什么? [英] What's a good way to dynamically render DOM elements with plain old JS?

查看:60
本文介绍了用普通的旧JS动态呈现DOM元素的好方法是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我面临的挑战是使用简单的旧Javascript构建单页应用程序,不允许使用任何库或框架。虽然在React和Angular中创建动态DOM元素非常简单,但是我想出的原始JS解决方案似乎很笨拙。我想知道是否存在一种特别简洁或更有效的方法来构建动态呈现的DOM元素?

The challenge I'm facing is to build a single-page app with plain old Javascript, no libraries or frameworks allowed. While creating dynamic DOM elements in React and Angular is fairly straightforward, the vanilla JS solution I've come up with seems clunky. I'm wondering if there's a particularly more concise or efficient way of building dynamically rendered DOM elements?

下面的函数接收从GET请求接收的数组,并为每个项目渲染一个div,传入值(就像您在React和呈现子元素)。

The function below takes in an array received from a GET request and renders a div for each item, passing in the value (much like you would map over results in React and render child elements).

 function loadResults(array) {
  array.forEach(videoObject => {
    let videoData =  videoObject.snippet;
    let video = {
       title : videoData.title,
       img : videoData.thumbnails.default.url,
       description : videoData.description
    };
    let div = document.createElement("DIV");
    let img = document.createElement("IMG");
    img.src = video.img;
    let h4 = document.createElement("h4");
    let title = document.createTextNode(video.title);
    h4.appendChild(title);
    let p = document.createElement("p");
    let desc = document.createTextNode(video.description);
    p.appendChild(desc);

    div.appendChild(img);
    div.appendChild(h4);
    div.appendChild(p);
    document.getElementById('results')
      .appendChild(div);
  });
}

这感觉不必要的笨拙,但我尚未找到更简单的方法

This feels unnecessarily clunky but I haven't yet found an easier way to do this.

谢谢!

推荐答案


注意:我在这里所说的都是关于证明的概念级别,仅此而已。它不会处理错误或异常情况,也不会在生产中测试
。可以自行决定使用。

Note: Everything I say here is on the proof of concept level and nothing more. It does not handle errors or exceptional cases, nor was it tested in production. Use at your own discretion.

一个好的方法是创建一个为您创建元素的函数。像这样:

A good way to go about would be to create a function that creates elements for you. Something like this:

const crEl = (tagName, attributes = {}, text) => {
  const el = document.createElement(tagName);
  Object.assign(el, attributes);
  if (text) { el.appendChild(document.createTextNode(text)); }

  return el;
};

然后您可以像这样使用它:

Then you can use it like so:

results
  .map(item => crEl(div, whateverAttributes, item.text))
  .forEach(el => someParentElement.appendChild(el));

我见过的另一个很酷的概念证明是使用 ES6代理作为一种模板引擎

Another cool proof of concept I've seen is the use of ES6 Proxies as a sort of templating engine.

const t = new Proxy({}, {
  get(target, property, receiver) {
    return (children, attrs) => {
      const el = document.createElement(property);
      for (let attr in attrs) {
        el.setAttribute(attr, attrs[attr]);
      }
      for (let child of(Array.isArray(children) ? children : [children])) {
        el.appendChild(typeof child === "string" ? document.createTextNode(child) : child);
      }
      return el;
    }
  }
})

const el = t.div([
  t.span(
    ["Hello ", t.b("world!")], {
      style: "background: red;"
    }
  )
])

document.body.appendChild(el);

代理将 get 捕获到目标对象上(为空),并呈现一个元素带有被调用方法的名称。这导致您在 const el = 中看到非常酷的语法。

The Proxy traps the get on the target object (which is empty), and renders an element with the name of the called method. This leads to the really cool syntax you see as of const el =.

这篇关于用普通的旧JS动态呈现DOM元素的好方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆