【问题标题】:create a class instance as html element [duplicate]创建一个类实例作为html元素[重复]
【发布时间】:2021-07-31 08:45:33
【问题描述】:

我想创建一个动态的 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
  • 非常感谢!
  • 说实话,这看起来是一样的原理,不是吗?所以,是的,它确实:-D 无法提前找到它...需要提高我的搜索技能...

标签: javascript html object


【解决方案1】:

使用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>

【讨论】:

  • 非常感谢!!!简直完美!
  • 感谢您的信任,点赞!
猜你喜欢
  • 2023-03-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多