javascript - 创建一个类实例作为 html 元素

标签 javascript html object

<分区>

我想创建一个动态的 HTML/JS 用户界面。 为此,我将动态创建对象,这些对象将在我的 html 中表示为一个按钮。 现在,我当然想跟踪点击事件。 如何将 addEventlistener 动态添加到按钮的这个特殊实例? (每个按钮创建自己的 svg 图标) 我的想法是,对象是按钮,但我不确定该怎么做......

我的想法是这样的:

class Lightbulb {
    /**
     * 
     * @param {String} id
     * @param {boolean} state 
     */
    constructor(id, state){
        this.id = id;
        this.state = state;
        /*
            create the icon here...
        */
        
        //is it somehow possible to achieve the following?
        this.addEventlistener("click", this.setState(!this.state));
    }
    /**
    *
    * {boolean} newState
    */
    setState(newState){
        console.log(newState)
    }

``

最佳答案

使用Web Components

真正归功于@Guerric P

直到今天我才听说过 Web 组件(在这种情况下)。我不得不说,我根据您的代码和 Guerric P 提供的文档制作了一个示例。您的代码实际上非常接近。我稍微清理了一下,但它与您的几乎相同。

您的想法不仅背后有深思熟虑,而且实际上是一项等待实现的 HTML5 技术。

class Lightbulb extends HTMLElement {
  state = false;
  /**
   * @param {String} id
   */
  constructor(id) {
    super();
    this.id = id;

    this.addEventListener("click", this.toggleState);
  }

  toggleState() {
    this.state = !this.state;
    this.classList.toggle("on", this.state);
  }
}

customElements.define("light-bulb", Lightbulb);
light-bulb.on {
  background-color: yellow;
}
<light-bulb>Clickable Lightbulb</light-bulb>

关于javascript - 创建一个类实例作为 html 元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67462103/

相关文章:

javascript - 图表加载后运行的 Highcharts 插件/扩展

javascript - HTML Canvas 意外改变颜色

javascript - 在向下滚动事件时更改 Logo 图像(并在向上滚动时再次将其更改回来)

c++ - MSVC 对象布局怪癖

javascript - 为什么我不能总结数组的所有属性?

javascript - Angular ng-show 不反射(reflect)变量的更改

php - 将姓名拆分为名字和姓氏

javascript - 如何将 DIV 上的填充底部转换为其包含的 DIV 上的负边距?

javascript - 使用对象 javascript 添加或附加对象

php - 防止对象出现多个实例