2011-02-18 25 views
2

我在與一個元素對象和jQuery的功能的問題:傳遞元素作爲變量起作用

HTML

<label for='state'>State</label> 
<input id='state' name='state' type='text' value=''/> 
<span class='info'><img class='tick' /><img class='cross' /></span> 

的JavaScript/jQuery的

var state = $("#state"); 

function validatefield(myelement) { 
    if (myelement.val().length > 3) { 
     alert("word"); 
    } else { 
     alert("sup"); 
    } 
} 
state.blur(validatefield(state)); 
state.keyup(validatefield(state)); 

沒有任何反應頁即使狀態輸入超過3個字符也是如此。

任何想法?

真棒 - 學習新的東西FTW

回答

6

無需爭論,在所有的事件處理程序綁定到的元素,這樣就可以使用函數內this關鍵字:

var state = $("#state"); 

function validatefield(event) { 
    if (this.value.length > 3) { // <-- use `this.value` instead 
     alert("word"); 
    } else { 
     alert("sup"); 
    } 
} 
state.blur(validatefield); 
state.keyup(validatefield); 

方式你正在嘗試它將實際調用該函數並將其返回值用作事件處理函數,這就是爲什麼什麼都沒發生:

// validatefield(state) is executed immediately and the return value, "undefined" 
// is passed as the first argument to state.blur() 
state.blur(validatefield(state)); 

要解決的其他情況是這樣,其中this關鍵字是不可用的,你應該使用匿名函數:在匿名函數

state.blur(function() { validatefield(state) }); 
+0

1這比礦使用回調事件參數一個更好的解決方案。 – Gazler 2011-02-18 12:30:59

+1

謝謝安迪 - 綠色刻度線來你的方式 – goingsideways 2011-02-18 12:32:33

2

裹的函數調用。

$(document).ready(function(){ 
    var state = $("#state"); 
    state.blur(function() {validatefield(state)}); 
    state.keyup(function() {validatefield(state)}); 
}); 

http://jsfiddle.net/eW8E8/1/

0

您應該使用匿名函數作爲jQuery的事件處理程序,而不是

state.keyup(validatefield(state)); 

使用

state.keyup(function() { 
    validatefield(state); 
}); 
0

不應該說,它是:

如果(米yelement.value.length> 3){