2009-12-18 73 views
2

我在下面的代碼中工作很好,我在jQuery中準備好的功能,當我填寫表單並將焦點從輸入元素更改爲另一個運行ajax檢查並分配一個CSS類到元素,顯示如果驗證或不。一切還好。如何在jQuery中定義函數?

id'喜歡用這個代碼定義一個函數,所以我也可以在頁面剛剛加載時調用它,所以如果表單填充在服務器端,並且模糊,但是我面對時也會執行檢查麻煩在jQuery中定義函數。

這是在模糊運行的代碼

$('#join_username').blur(function(){ 
    $('#join_username').addClass(\"join_form_input_checking\"); 
    $('#join_username').removeClass(\"join_form_input\");  
    $('#join_username').removeClass(\"join_form_input_error\");  
    $('#join_username').removeClass(\"join_form_input_verified\");  


    $.post(\"inc/viewlets/join_form/check_username.php\", { 
      join_username: $('#join_username').val() 
      }, 
      function(response){ 
        setTimeout(\"finishAjaxUsername('usernameResult', '\"+escape(response)+\"')\", 400); 
     if(escape(response)=='true') joinFormCheck[0]=true;  
     else joinFormCheck[0]=false; 

     checkFormArray(joinFormCheck);   
      } 
     );    

    return false; 
}); 
+0

你爲什麼要逃避字符串分隔符? – kiamlaluno 2009-12-18 18:02:58

回答

15

或者你可以使用使用普通函數的語法

function do_on_blur(){ 
    // your base. I'm in it 
} 

$("#join_username").blur(do_on_blur); 
15

簡單地定義,而不是傳遞blur()一個匿名函數的函數:

$.myFunctionName = function() 
{ 
    // your code here 
} 

$("#join_username").blur($.myFunctionName); 

如果你想在迴應被調用的函數一個事件(比如document.ready),就像調用普通函數一樣調用它。

$(document).ready(function() 
{ 
    // -- define your function 
    $.myFunctionName = function() 
    { 
     //your code here 
    } 

    // -- add a callback to blur on an input 
    $("#join_username").blur($.myFunctionName); 

    // -- manually call the function once 
    $.myFunctionName(); 
}); 
+0

謝謝! 現在...我在ready()中定義了函數,在頁面加載時如何運行此函數。 我想檢查表單元素,因爲它的加載,如果它有一個值=「我的字符串在這裏」屬性 – Mike 2009-12-18 15:58:17

+0

只需調用它就像你會正常的功能。所以,如果你希望它在文檔準備就緒以及$(document).ready(function(){$ .myFunctionName();}); – typeoneerror 2009-12-18 16:11:42

+0

謝謝你!這真的是我正在尋找的! – Mike 2009-12-18 16:19:21

0

我認爲你有無效的語法在這裏:

$('#join_username').blur(function(){ 
    $(this) 
     .addClass("join_form_input_checking") 
     .removeClass("join_form_input");  
     .removeClass("join_form_input_error");  
     .removeClass("join_form_input_verified");  


    $.post("inc/viewlets/join_form/check_username.php", { 
     join_username: $(this).val() 
    }, function(response) { 
     setTimeout(function() { 
     finishAjaxUsername('usernameResult', escape(response)) 
     }, 400); 
     if(escape(response)=='true') { joinFormCheck[0]=true; } 
     else { joinFormCheck[0]=false; } 
     checkFormArray(joinFormCheck);   
    });     

    return false; 
}); 

嘗試。然後,當然,如果你想要的功能是從,你可以簡單地把它分配給一個變量模糊事件獨立...所以你最終用:

var blurFunc = function() { ...function from above... }; 
$('#join_username').blur(blurFunc); 
0

如果你不希望創建一個jQuery插件,那麼它足以傳遞給jQuery的功能,您要使用的函數的引用。當您僅需要該功能一次時,就會使用匿名功能。

function blur() {}; 

$('#join_username').blur(blur); 

通常在函數被多次使用時完成;通常情況下,您將使用匿名功能。