开发者

Javascript, problem with binding an event to a div-tag

开发者 https://www.devze.com 2022-12-23 01:55 出处:网络
i am trying to bind an event to a dynamically created div. function GameField(playerNumber) { this.fields = new Array();

i am trying to bind an event to a dynamically created div.

function GameField(playerNumber) {
this.fields = new Array();
this.player = playerNumber;
this.isPlayerActive = false;
this.currentRound = 0;
}

GameField.prototype.InitField = function(fieldNumber) {
    var newField = document.createElement("div");
    if (fieldNumber == 0 || fieldNumber == 6 || fieldNumber == 8 || fieldNumber == 17)
        newField.className = 'gameCellSmall borderFull gameText gameTextAlign';
    else
        newField.className = 'gameCellSmall borderWithoutTop gameText gameTextAlign';
    newField.onclick = function() { this.DivClick('a'); }
    this.fields[fieldNumber] = newField;
    return newField;
}

GameField.prototype.DivClick = function(fieldNumber) {
    alert('Nummer: ' + fieldNumber);
}

Everything works perfectly, but when you click on one of the created divs, i end up with the following error message: Error: Object doesn't support this property or method.

If i replace the onclick function with this, then it works:

开发者_运维技巧
newField.onclick = function() { alert('Nummer: ' + fieldNumber); }

How can i get the onclick event to fire my DivClick function instead?


The problem is that the onclick event handler gets executed with the this value pointing to the DOM element that triggered the event, so that's why executing this.DivClick fails.

You need to enforce the context, in order to use instance methods within the event handler, for example, you could store a reference to the current instance:

GameField.prototype.InitField = function(fieldNumber) {
    var newField = document.createElement("div");
    //...
    var instance = this;
    newField.onclick = function() { instance.DivClick('a'); }
    //...
}


That is the way

function DivClick (fieldNumber) {
        alert('Nummer: ' + fieldNumber);
    }

{ this.DivClick('a'); } - should be replaced to { DivClick('a'); }

0

精彩评论

暂无评论...
验证码 换一张
取 消