Javascript 操纵对象';事件处理程序中时的属性
我了解到,由于作用域的原因,事件侦听器中嵌入在对象中的Javascript 操纵对象';事件处理程序中时的属性,javascript,this,Javascript,This,我了解到,由于作用域的原因,事件侦听器中嵌入在对象中的this关键字并不是指全局对象,而是指触发事件的元素 现在,我明白了,如果我想获取属性,我可以在调用事件处理程序之前将其保存到变量中。但是如果我想操纵财产的价值,我该怎么办呢 在下面的代码中,我试图在removeDrug事件侦听器中操作drugCount属性 var Drugs = { drugs: $("#drugs_table"), drugRow: $("#drug").html(), drugCount: 0
this
关键字并不是指全局对象,而是指触发事件的元素
现在,我明白了,如果我想获取属性,我可以在调用事件处理程序之前将其保存到变量中。但是如果我想操纵财产的价值,我该怎么办呢
在下面的代码中,我试图在removeDrug
事件侦听器中操作drugCount
属性
var Drugs = {
drugs: $("#drugs_table"),
drugRow: $("#drug").html(),
drugCount: 0,
init: function() {
this.addDrugRow();
this.removeDrugRowHandler();
},
addDrugRow: function() {
this.drugCount++;
this.drugs.append(this.drugRow.replace(/{{id}}/,this.drugCount));
$(".drugsSelect").select2();
},
removeDrugRowHandler: function() {
drugCount = this.drugCount;
// also a problematic solution, because it only retains the inital drugCount.
// i.e I need a way to access the "live" count from within the event
$(document).on("click",".removeDrug",function(){
if (drugCount>0) {
$(this).parents("tr").remove();
this.drugCount--; // how should I approach this?
}
});
}
}
试试这个
var Drugs = function() {
var me = this;
me.drugs = $("#drugs_table");
me.drugRow = $("#drug").html();
me.drugCount = 0;
me.init = function() {
this.addDrugRow();
this.removeDrugRowHandler();
};
me.addDrugRow = function() {
this.drugCount++;
this.drugs.append(this.drugRow.replace(/{{id}}/,this.drugCount));
$(".drugsSelect").select2();
};
me.removeDrugRowHandler= function() {
var drugCount = me.drugCount;
$(document).on("click",".removeDrug",function(){
if (drugCount>0) {
$(this).parents("tr").remove();
me.drugCount--;
}
});
}
}
事实证明,简单的解决方案是使用对象名,而不是上下文
this
。
因此,我没有使用这个.drugCount
而是使用药物.drugCount
但是,只有在单个对象的上下文中,此解决方案才有效。如果我要编写一个“类”(即var-druges=function(){…}
),这将不起作用