Javascript,将事件绑定到div标记时出现问题
我正在尝试将事件绑定到动态创建的divJavascript,将事件绑定到div标记时出现问题,javascript,function,html,prototype,onclick,Javascript,Function,Html,Prototype,Onclick,我正在尝试将事件绑定到动态创建的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.c
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);
}
一切工作都很完美,但当您单击其中一个创建的div时,我会看到以下错误消息:error:Object不支持此属性或方法
如果我将onclick函数替换为以下函数,则它可以工作:
newField.onclick = function() { alert('Nummer: ' + fieldNumber); }
如何让onclick事件触发我的DivClick函数?问题是执行
onclick
事件处理程序时,this值指向触发事件的DOM元素,因此执行this.DivClick
失败
您需要强制上下文,以便在事件处理程序中使用实例方法,例如,您可以存储对当前实例的引用:
GameField.prototype.InitField = function(fieldNumber) {
var newField = document.createElement("div");
//...
var instance = this;
newField.onclick = function() { instance.DivClick('a'); }
//...
}
就是这样
function DivClick (fieldNumber) {
alert('Nummer: ' + fieldNumber);
}
{this.DivClick('a');}-应替换为{DivClick('a');}