2014-11-24 50 views
0

我試圖創建一個函數來遍歷一些錶行,但我需要使用this.isempty而不是isempty。我如何在每個循環內部訪問它。OOP - 在每個內部訪問公共「this」

編號:

function checkValues(look) { 
    this.isempty = 1; 
    this.search = $(look).find("input").each(function(){       
     if ($.trim($(this).val())!="") { 
      this.isempty = 0; 
     } 
    }); 
    return this.isempty; 
} 

顯然this.isempty = 0;將無法​​正常工作。我怎樣才能做到這一點?

回答

2

您可以使用一個閉包變量在這種情況下指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) { 
    this.isempty = 1; 
    this.search = $(look).find("input").; 
    this.isempty = this.search.filter(function() { 
     return $.trim(this.value) != ''; 
    }).length > 0; 
    return this.isempty; 
} 
+0

第一種方法,我意識到使用每個不是最好的辦法,但是是var self = this;正確的方式呢? – FirstLegion 2014-11-24 03:24:16

+0

@FirstLegion AFAIK在這種情況下是最好的方式 – 2014-11-24 03:26:54

+0

好的,謝謝。 – FirstLegion 2014-11-24 03:34:48

0

你需要引用this由於您的代碼中的約束?以下工作?

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; 
} 
+0

在每個循環中返回false都不起作用,因爲它只是退出每個循環。它在這種情況下用作「休息」。另外,不告訴我如何使用每個內部的「this」。 – FirstLegion 2014-11-24 03:22:00

+0

從你給的樣本中,你不需要訪問'this'。你是否使用這個方法作爲構造函數,你需要在'this'上存儲值? – rdubya 2014-11-24 03:27:41

+0

我只是舉了一個例子,因爲我想知道如何爲其他情況做到這一點。謝謝你。 – FirstLegion 2014-11-24 03:30:47

相關問題