javascript - 是否可以将 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 实例作为子类附加到其父类)
这可能吗?如果是这样,如何以及最好的实施方式是什么?如果没有,我至少可以做类似的事情来达到类似的结果吗?
提前致谢。
解决方案
网络实际上支持自定义元素,你可以这样做:
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 组件。
推荐阅读
- javascript - Javascript 编码检查器 ASCII/UFT8
- apache-nifi - 如何在 MiNifi config.yml 中设置“nifi.remote.input.http.enabled=true”
- sql - 无论条件如何,T-SQL If 子句都在计算
- angular - 与 React/Angular 的跨浏览器兼容性
- javascript - 从地址列表加载谷歌地图时遇到问题
- php - 根据选定的数据库记录设置下拉列表的值
- java - 用文字值替换字符串中的 ascii 或 unicode
- c++ - 比 C++ 中的 OpenCV 库更快地获取总帧数和 FPS
- python - 将 Django Admin 站点中的用户添加到网页上的 html 表中
- php - 关系在 Laravel 中不起作用