2013-05-14 55 views
0

我有這個函數應該返回一個對象,當它發現它,但它不這樣做。 我在做什麼錯?jquery函數返回對象

var getEl = function(title){ 
    var theInputs = $('input[type=text], input[type=radio], input[type=checkbox], select, textarea') 
    theInputs.each(function(){ 
     if (this.title==title){ 
      getEl = this 
      console.log('found it!') 
     } 
    }) 
} 

console.log(getEl('Office Status')) 

我知道,它的作品,因爲發現它是在控制檯上的輸出,但控制檯報告不確定的,因爲這行的輸出:

console.log(getEl('Office Status')) 
+1

哪裏'return'語句返回元素? –

+0

你有可能在某些時候用vbscript開發過嗎?我想我已經看到了通過將它分配給之前的函數名稱來返回值的模式。 –

+0

爲什麼不只是使用過濾功能? –

回答

2
var getEl = function(title){ 
    var result; 
    var theInputs = $('input[type=text], input[type=radio], input[type=checkbox], select, textarea') 

    theInputs.each(function(){ 
     if (this.title==title){ 
      result = this 
      console.log('found it!') 
      return false; // break the loop 
     } 
    }); 

    return result; 
} 

重寫的功能變量的值不行。你想要返回結果。

編輯:

話雖這麼說,你應該能夠真正與此更換整個事情:

var $result = $(":input[title='" + title + "']"); 

if(result.length > 0) return $result[0]; 

雖然這將需要一些修改,如果你確實需要專門只獲取這3種類型的輸入,而不是任何輸入。像這樣的事情(使用現有的theInputs變量):

var $result = theInputs.filter("[title='" + title + "']"); 
+0

等待這麼久,您可以取消刪除您的帖子。 +1 –

+0

@Vega奇怪,我編輯後立即刪除。猜猜有一些滯後。 –

1

你需要從你的函數

var getEl = function(title){ 
    var el; 
    var theInputs = $('input[type=text], input[type=radio], input[type=checkbox], select, textarea') 
    theInputs.each(function(){ 
     if (this.title == title){ 
      el = this; 
      return false; 
     } 
    }) 
    return el; 
} 
+1

請在'return'語句後刪除'console.log'。 –

+1

在'each'內返回非錯誤與標準循環中的「continue」相同。這不會'工作。 –

+0

@JamesMontagne ..是的,更新.. –