gpt4 book ai didi

javascript - 如何将事件监听器添加到由 javascript 对象模型生成的 HTML

转载 作者:行者123 更新时间:2023-12-03 00:08:25 25 4
gpt4 key购买 nike

<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 实例生成的按钮添加一个事件监听器。我该如何去做呢?

最佳答案

尽管您可以使用内联处理程序,对当前代码进行最少的调整,但它们是非常糟糕的做法 - 相反,创建 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>

关于javascript - 如何将事件监听器添加到由 javascript 对象模型生成的 HTML,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54858932/

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