【问题标题】:How to add event listener to HTML generated by javascript object model如何将事件侦听器添加到由 javascript 对象模型生成的 HTML
【发布时间】:2019-02-25 03:01:58
【问题描述】:
<div class="target">

</div>

<script>
    class Shape {
        constructor (id, x, y) {
            this.id = id
            this.x = x
            this.y = y
            this.display()
        }

        display() {
            return 
            `
            <div class="square">
                <button class="square-button"></button>
            </div>
            `
        }
    }

    var square = new Shape(0, 5, 5);

    $('.target').html(square.display());
</script>

我想为将通过每个 Shape 实例生成的按钮添加一个事件侦听器。我该怎么做呢?

【问题讨论】:

    标签: javascript html javascript-objects addeventlistener


    【解决方案1】:

    虽然您可以使用内联处理程序对当前代码进行最少的调整,但它们是非常糟糕的做法 - 相反,创建 HTML 元素(不仅仅是一个字符串),并将侦听器附加到它:

    class Shape {
      constructor(id, x, y) {
        this.id = id
        this.x = x
        this.y = y
        this.display()
      }
    
      display() {
        const sq = $(`
                <div class="square">
                    <button class="square-button">button</button>
                </div>
        `);
        sq.on('click', 'button', () => console.log('click'));
        return sq;
      }
    }
    
    var square = new Shape(0, 5, 5);
    
    $('.target').append(square.display());
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <div class="target">
    
    </div>

    【讨论】:

      【解决方案2】:

      例如在事件中使用 jquery 文档

      $(document).on('click', '. square-button', handler)
      
      function handler() {
        var $that = this; // the button which was click
        // do stuff etc...
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2018-12-10
        • 2014-01-29
        • 1970-01-01
        • 2012-09-09
        • 1970-01-01
        • 2021-04-17
        • 2019-03-21
        相关资源
        最近更新 更多