gpt4 book ai didi

javascript - 利用 customElements 在 javascript 中创建页面构建框架

转载 作者:行者123 更新时间:2023-12-02 20:53:46 24 4
gpt4 key购买 nike

我和我的 friend 正在尝试制作一个 JavaScript 框架,允许用户制作元素并自定义它们。以及以某种方式管理它们。

我们希望能够以某种方式制作这样的自定义元素

class Header extends HTMLElement {

constructor() {
super();

}

connectedCallback(){

this.title = this.getAttribute("title")
console.log(this.getAttribute("title"))

if(this.hasAttribute("drawer-button")){

}

this.innerHTML =
`
<div class="--e-header-1">
<e-button></e-button>
<div class="header-title">
<h1>${this.title}</h1>
</div>
</div>
`
}

}

customElements.define('e-header', Header);

很酷的是,您可以像这样在 HTML 中使用它 <e-header></e-header>但我们希望我们能做这样的事情


var el = new Header(//put in options maybe);
document.append(el)

我们不断收到此错误Uncaught TypeError: Illegal constructor

我们将如何去做这样的事情以及我们是否走在正确的轨道上

最佳答案

你想做这样的事情吗?

我已将选项 title 传递给类并在类中进行设置。

class Header extends HTMLElement {

constructor(options) {
super();
this.title = options.title;
}

connectedCallback() {
this.title = this.getAttribute("title")
console.log(this.getAttribute("title"))

if (this.hasAttribute("drawer-button")) {

}

this.innerHTML =
`
<div class="--e-header-1">
<e-button></e-button>
<div class="header-title">
<h1>${this.title}</h1>
</div>
</div>
`
}

}

customElements.define('e-header', Header);

var el = new Header({
'title': 'headerTitle'
});
document.body.append(el)

关于javascript - 利用 customElements 在 javascript 中创建页面构建框架,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61539832/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com