我有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);
答案 0 :(得分:0)
使用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);
&#13;
<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>
&#13;