【问题标题】:Creating custom elements doesn't work - createElement()创建自定义元素不起作用 - createElement()
【发布时间】:2021-06-23 14:12:11
【问题描述】:

我正在努力让我的项目对我自己来说是可读的,并且我正在尝试创建新的自定义 HTML 元素。

document.createElement("name", {is: "h2"});
document.createElement("avatar", {is: "img"});
document.createElement("description", {is: "p"});

这就是我使用它们的方式

$(`<avatar class="dropshadow" src="${friend.avatar}">`).appendTo(box);
$(`<name class="name">${friend.name}</name>`).appendTo(box);
$(`<description class="noselect">${friend.description}</description>`).appendTo(box);

很遗憾,这些都不起作用。它们不被视为继承的元素。 检查节点时,原型是HTMLUnknownElementPrototype,这告诉我它不起作用。 我在这里做错了什么?这没有意义。

【问题讨论】:

  • 我不认为这是他们的工作方式。查看documentation
  • 我已经多次查看文档,但我尝试的一切都不起作用。我无法用它创建自己的元素。

标签: javascript html createelement


【解决方案1】:

createElement的第一个参数是标签名。

const name = document.createElement('h2');
const avatar = document.createElement('img');
const description = document.createElement('p');

【讨论】:

  • 设置变量名不会反映它在 DOM 中的标签名。它不会显示为&lt;avatar&gt;,而只是&lt;img&gt;
【解决方案2】:

好吧,我是不是很笨 自定义元素不能使用createElement() 创建,但可以使用customElements.define() 创建,限制是标签名称必须包含连字符。

Look here

【讨论】:

  • 我会在那时和那里做,但stackoverflow说我可以在23小时内接受答案,我仍然不能接受13小时内的答案
猜你喜欢
  • 2018-10-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-12-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多