我正在尝试在表中显示数据库,允许用户单击时编辑每条记录。我有一个创建数据库对象的构造函数。我正在循环访问我的数据库来显示它。这是部分代码:
for (var j = 1; j <this.data.length; j++) {
var html = '<div id="this.data[j] + '"';
html += 'onclick="this.edit_record (\''+this.data[j]+'\')">'+this.data[j]+'</div>';
}
$("#table").append(html);
调用 this.edit_record 不起作用。我怎样才能纠正它?谢谢。
最佳答案
没有必要在html本身中编写onclick
。
你可以这样处理:
查看代码注释。
for (var j = 1; j <this.data.length; j++) {
// create html
var html = '<div id="' + this.data[j] + '"';
html += this.data[j] + '</div>';
// create new jQuery element
var e = $(html);
// set click handler.
var self = this; // closure for this
(function(x) { // iterator closure for j
e.click(function() {
self.edit_record(self.data[x])
});
})(j);
// append element.
$("#table").append(e);
}
function Demo() {
this.data = ["foo", "bar", "baz"];
this.edit_record = function(data) {
alert(data);
}
for (var j = 0; j < this.data.length; j++) {
// create html
var html = '<div id="' + this.data[j] + '">';
html += this.data[j] + '</div>';
// create new jQuery element
var e = $(html);
// set click handler.
var self = this; // closure for this
(function(x) { // iterator closure for j
e.click(function() {
self.edit_record(self.data[x])
});
})(j);
// append element.
$("#table").append(e);
}
return this;
}
var demo = new Demo();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="table">
</div>
关于javascript - 如何使用 html 中的 "this"关键字调用对象的方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27663628/