[英]How do I create an event listener on a property in every instance of a class?
我有5個對象(即類的實例),並且需要在“ im”屬性上設置一個事件偵聽器,該屬性運行函數“ squash()”。
我試圖在this.im.click(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>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.