0

オブジェクトが見つかったときにオブジェクトを返すはずのこの関数がありますが、そうしていません。私は何を間違っていますか?

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'))

コンソールに出力されていることがわかったので機能することはわかっていますが、コンソールは次の行の出力として undefined を報告します。

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

2 に答える 2

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

functions 変数の値を上書きしても機能しません。代わりに結果を返したいとします。

編集:

そうは言っても、実際にはすべてをこれで置き換えることができるはずです:

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

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

ただし、任意の入力ではなく、これら 3 種類の入力のみを具体的に取得する必要がある場合は、いくつかの変更が必要になります。このようなもの(既存のtheInputs変数を使用):

var $result = theInputs.filter("[title='" + title + "']");
于 2013-05-14T19:45:15.437 に答える
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;
}
于 2013-05-14T19:45:42.007 に答える