Javascript 面向对象-访问公共资源”;这";每个内部
我试图创建一个函数来循环一些表行,但我需要使用this.isempty而不是isempty。我如何在each循环中访问它 代码:Javascript 面向对象-访问公共资源”;这";每个内部,javascript,jquery,Javascript,Jquery,我试图创建一个函数来循环一些表行,但我需要使用this.isempty而不是isempty。我如何在each循环中访问它 代码: 显然this.isempty=0将不起作用。如何执行此操作?在本例中,您可以使用闭包变量来引用isempty function checkValues(look) { this.isempty = 1; var self = this; this.search = $(look).find("input").each(function () {
显然
this.isempty=0代码>将不起作用。如何执行此操作?在本例中,您可以使用闭包变量来引用isempty
function checkValues(look) {
this.isempty = 1;
var self = this;
this.search = $(look).find("input").each(function () {
if ($.trim($(this).val()) != "") {
self.isempty = 0;
}
});
return this.isempty;
}
但这里更合适的方法是像这样使用.filter()
由于代码中的约束,是否需要引用此
?下面的方法行吗
function checkValues(look) {
var isEmpty = 1;
$(look).find("input").each(function(){
if ($.trim($(this).val())!="") {
isEmpty = 0;
return false; // Breaks out of the loop for a little performance boost
}
});
return isEmpty;
}
在each循环中返回false不起作用,因为它只是退出each循环。在这种情况下,它起到了“中断”的作用。另外,并没有告诉我如何在每个文件中使用“this”。从您提供的示例中,您不需要访问
this
。您是否将此方法用作需要在上存储值的构造函数?我只是举了一个例子,因为我想知道如何在其他情况下执行此操作。不过谢谢你。对于第一种方法,我意识到使用each并不是最好的方法,而是var self=this;正确的方法是什么?@FirstLegion AFAIK在这个场景中,这是最好的方法
function checkValues(look) {
this.isempty = 1;
this.search = $(look).find("input").;
this.isempty = this.search.filter(function () {
return $.trim(this.value) != '';
}).length > 0;
return this.isempty;
}
function checkValues(look) {
var isEmpty = 1;
$(look).find("input").each(function(){
if ($.trim($(this).val())!="") {
isEmpty = 0;
return false; // Breaks out of the loop for a little performance boost
}
});
return isEmpty;
}