2013-05-14 193 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 ..是的,更新.. –