我在为 DOM 中动态生成的元素编写处理程序时遇到问题。
我的对象由一些属性和一些方法组成
function JMaze(c,r,selector) {
this.maze = new Array();
this.content = new Array();
this.c = c;
this.r = r;
this.x = 0;
this.y = 0;
this.selector = selector; //need a DOM place to fit with the maze
this.bookmark = "Home";
//...other methods...
this.goTo = function(event){
console.log("HERE");
var maze = this.maze;
var bookmark = this.bookmark;
var start, destination;
for (i = 0; i < c; i++)
for (j = 0; j < r; j++)
if (maze[i][j].id == bookmark)
start = maze[i][j];
for (i = 0; i < c; i++) {
for (j = 0; j < r; j++) {
if (maze[i][j].id == event.data.id)
destination = maze[i][j];
}
}
var p = this.findShortestPathAndGo(start,destination);
this.renderMaze(p);
};
this.showMenu = function() {
var content = this.content;
var div = "<div class=\'jMenu\'>";
$.each(content, function(index, value) {
div += "<div menuval=\'" + value.id + "\'>" + value.id + "</div>";
});
div += "</div>";
$( "body" ).append(div);
$.each(content, function(index, value) {
$("[menuval='" + value.id + "']").on(
"click", //event
{id: value.id}, //data
**this.goTo** //handler
);
});
};
};
当我调用 showMenu 时,一切正常,并且靠近末尾的 block 执行了预期的操作,将 DOM 对象上的点击与属性 menuval 绑定(bind)到正确的值。 但是当我点击并调用处理程序时,Chrome 调试会这样说
在jquery.min.js:3中找到错误。
实际上,它永远不会进入 goTo 函数。
周围有人可能知道为什么吗?
提前致谢。
最佳答案
回答
首先,您需要保留对 JMaze
的引用对象,如果你想在回调中使用它,就像这样:
var that = this;
然后,您需要确保JMaze.goTo
有适当的上下文,意思是 this
将引用JMaze
对象,您可以使用 jQuery.proxy
来完成此操作函数,像这样:
$.proxy(that.goTo, that);
所以,把它们放在一起:
this.showMenu = function() {
var that = this;
var content = this.content;
var div = "<div class=\'jMenu\'>";
$.each(content, function(index, value) {
div += "<div menuval=\'" + value.id + "\'>" + value.id + "</div>";
});
div += "</div>";
$( "body" ).append(div);
$.each(content, function(index, value) {
$("[menuval='" + value.id + "']").on(
"click", //event
{id: value.id}, //data
$.proxy(that.goTo, that) //handler
);
});
};
您可以看到它正在运行 here 。我添加了一些基本数据只是为了测试它。
建议
我强烈建议您利用 jQuery 动态创建新 DOM 元素的方式 ( docs ) 并重写整个函数,如下所示:
this.showMenu = function () {
var that = this;
var div = $('<div/>').addClass('jMenu');
$.each(this.content, function (index, value) {
$('<div/>')
.attr('menuval', value.id)
.text(value.id)
.appendTo(div)
.on('click', { id: value.id }, $.proxy(that.goTo, that));
});
$('body').append(div);
};
关于javascript - JQuery 和未捕获的类型错误 : undefined is not a function - no clues about the real pitfall,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24548768/