![](/img/trans.png)
[英]How do I invoke a JS object (such as datepicker) method using the HTML id?
[英]How do you invoke a method on an object using the “this” keyword in html?
我正在尝试在一个表中显示一个数据库,该数据库允许用户在单击时编辑每个记录。 我有一个创建数据库对象的构造函数。 我正在遍历数据库以显示它。 这是代码的一部分:
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>
this
onclick引用了clicked元素。 当您使用jquery时,最好的事情是这样的:
var html="", mythis=this; // save "this" (your object) context
for (var j = 1; j <this.data.length; j++) {
html += '<div data-id="'+this.data[j] + '">'+this.data[j]+'</div>';
}
$("#table").append(html); // append all html at once, faster!
// assign a click handler to all divs children of #table
$("#table>div").click(function() {
// inside this function, this is the clicked element (so this.getAttribute("data-id") would be the id
// and mythis would be the saved this (your object)
mythis.edit_record(this.getAttribute("data-id"));
});
您可以通过向对象分配全局onclick="mysavedthis.edit_record..."
,然后像onclick="mysavedthis.edit_record..."
这样编写HTML onclick的方式来实现,但是由于您已经在使用jquery,因此最好以编程方式分配click处理程序,因为这样可以不太脆弱(您无需编码引号,考虑data []有引号的情况,使用全局vars ...)。
请注意,我分配了data-id
而不是分配“ id
”。 这是因为ID必须是唯一的 ,因此要100%符合标准并在data []数组中支持重复值,只需选择另一个属性名称而不是id。 约定建议对用户定义的属性使用数据前缀。
似乎您缺少单引号。 更新了我的答案以解决此问题
var parent = this;
for (var j = 0; j < this.data.length; j++) {
var currentValue = this.data[j];
var html = '<div id="' + currentValue + '"';
html += '>' + currentValue + '</div>';
$('#table').append(html);
$('#'+currentValue).click(function(){
parent.edit_record ($(this).attr("id"));
});
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.