首页 > 解决方案 > 是否可以将 document.createElement 和 appendChild 的操作减少到 JS 中的一个命令中?

问题描述

我正在尝试创建一个对象,该对象创建它的实例将像 document.createElement() 一样,具有额外的好处,即类可以从它扩展,加上传递给它的父元素,它会自动 appendChild 本身至。

例如:

class Player extends Model {
 constructor(parent, att0, att1) {
  super(parent, "div");
  
  let attribute0 = new Model(this, "h5");
  let attribute1 = new Model(this, "h5");
  
  attribute0.innerText = att0;
  attribute1.innerText = att1;
 }
}

代替:

class Player{
 constructor(att0, att1) {
  
  let attribute0 = document.createElement("h5");
  let attribute1 = document.createElement("h5");
  
  attribute0.innerText = att0;
  attribute1.innerText = att1;

  this.appendChild(attribute0);
  this.appendChild(attribute1);
 }
}

(并将 Player 实例作为子类附加到其父类)

这可能吗?如果是这样,如何以及最好的实施方式是什么?如果没有,我至少可以做类似的事情来达到类似的结果吗?

提前致谢。

标签: javascript

解决方案


网络实际上支持自定义元素,你可以这样做:

class Player extends HTMLDivElement {
  constructor() {
    this.appendChild(document.createElement('h2'));
    this.lastElementChild.textContent = this.dataset.title;
    this.appendChild(document.createElement('h4'));
    this.lastElementChild.textContent = this.dataset.subtitle;
  }
}
customElements.define('player-wrapper', Player, { extends: 'div' });

然后渲染它:

<player-wrapper subtitle='foo' title='bar' />

你可以在 MDN 上阅读它。

您也可以将子项作为属性等,尽管通常在受支持的模板中完成声明性组合。

通常 - 人们只是为此使用一些组件系统,例如 Angular/React/Vue,而不是使用“原始”Web 组件。


推荐阅读