簡體   English   中英

如何為對象添加事件偵聽器?

[英]How can I add event listener for an object?

在為該對象編寫成員函數時,如何將addEventLisener到該對象時遇到麻煩。

我有一個名為Grid的類,該類具有創建HTML div元素的成員函數create 現在,我想向該div添加一個事件監聽器,該事件監聽器等待click 這是代碼。

請注意,我還有另一個網格成員函數的update

Grid.prototype.create = function(index) {
    var newnode = document.createElement("div");
    newnode.setAttribute("class", "grid");
    newnode.setAttribute("id", "grid" + index);
    newnode.style.width = this.width + "px";
    newnode.style.height = this.height + "px";
    document.getElementById("whole").appendChild(newnode);

    newnode.addEventListener("click", function() {
        if (this.live) {
            this.live = false;
        } else {
            this.live = true;
        }
        this.update(index);
    }, false);

    this.update(index);
 };

問題是, this代表了addEventListener塊內的HTML DIV Object ,但我需要將其作為Grid Object以便可以調用update函數。

如何解決這個問題呢? 還是在創建包含對象的div時添加對象的偵聽器的另一種方法?

只需使用在事件處理程序范圍之外聲明的變量

Grid.prototype.create = function(index) {
    var grid    = this,
        newnode = document.createElement("div");

    newnode.className    = "grid";
    newnode.id           = "grid" + index;
    newnode.style.width  = this.width + "px";
    newnode.style.height = this.height + "px";

    newnode.addEventListener("click", function() {

        grid.live = !grid.live;
        grid.update(index);

    }, false);

    document.getElementById("whole").appendChild(newnode);

    this.update(index);
 };

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM