gpt4 book ai didi

javascript - 如何在类的每个实例中的属性上创建事件监听器?

转载 作者:行者123 更新时间:2023-11-28 03:54:09 26 4
gpt4 key购买 nike

我有 5 个对象(即类的实例),我需要在“im”属性上设置一个事件监听器,该属性运行函数“squash()”。

我尝试在类中使用 this.im.click(squash()),但这不起作用。如何创建事件监听器?

let divs = $(".flies");
divs.each(function(i){
let img = $("<img/>");
img.attr({
"id": i,
"src": "http://clipart-library.com/images/8iznoLG8T.png"});
$(this).append(img)
});

class Fly {
constructor(div, im, alive){
this.div = div;
this.im = im;
this.alive = true;
}
squash(){
this.alive= false;
this.element.css("visibility", "hidden");
}
}

let fly1 = new Fly($('#fly1'), $('#0'), true);
let fly2 = new Fly($('#fly2'), $('#1'), true);
let fly3 = new Fly($('#fly3'), $('#2'), true);
let fly4 = new Fly($('#fly4'), $('#3'), true);
let fly5 = new Fly($('#fly5'), $('#4'), true);

最佳答案

使用im.click(this.squash.bind(this));

class Fly {
constructor(div, im, alive){
this.div = div;
this.im = im;
this.alive = true;
this.init()
}

init(){
this.im.click(this.squash.bind(this));
}

squash(){
this.alive= false;
// wasn't sure what `element` is supposed to be, used `div` instead
this.div.css("visibility", "hidden");
}
}

let fly1 = new Fly($('#fly1'), $('#0'), true);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="0">Click to hide content</button>

<div id="fly1">Content 1</div>

关于javascript - 如何在类的每个实例中的属性上创建事件监听器?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47717382/

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