2012-02-19 133 views
0

我似乎無法得到這個工作:下面的代碼:jQuery回調函數?

// Clears the default text on click, but restores if nothing is entered 
var clearText = (function(){ 
    $("input:text").each(function() { 

     var default_value = this.value; 

     $(this).focus(function(){ 
       if(this.value == default_value) { 
         this.value = ''; 
       } 
     }); 

     $(this).blur(function(){ 
       if(this.value == '') { 
         this.value = default_value; 
       } 
     }); 

    }); 

    $("textarea").each(function() { 

     var default_value = this.value; 

     $(this).focus(function(){ 
       if(this.value == default_value) { 
         this.value = ''; 
       } 
     }); 

     $(this).blur(function(){ 
       if(this.value == '') { 
         this.value = default_value; 
       } 
     }); 

    }); 

})(); 


$('html').on('keydown', 'body', function(e){ 
    if (e.which == 9) 
    { 
     clearText(); 
    } 
}); 

明文()肯定是被稱爲在頁面加載,但隨後並沒有作爲一個回調函數工作呢?我不完全確定爲什麼,有誰能幫我解決問題?

乾杯

回答

2

clearText是未定義的,它不是函數。你正在調用它,因爲你認爲你正在定義它。這就是函數賦值最後的()。

var clearText = function(){ 
    $("input:text").each(function() { 

     var default_value = this.value; 

     $(this).focus(function(){ 
       if(this.value == default_value) { 
         this.value = ''; 
       } 
     }); 

     $(this).blur(function(){ 
       if(this.value == '') { 
         this.value = default_value; 
       } 
     }); 

    }); 

    $("textarea").each(function() { 

     var default_value = this.value; 

     $(this).focus(function(){ 
       if(this.value == default_value) { 
         this.value = ''; 
       } 
     }); 

     $(this).blur(function(){ 
       if(this.value == '') { 
         this.value = default_value; 
       } 
     }); 

    }); 

}; 

現在的功能是可調用

+0

有沒有一種方法可以讓它在自定義時自動調用,並且使clearText成爲一個函數? – chintanparikh 2012-02-19 07:42:39

+0

是的,有幾種方法可以做到這一點。但是不要保存一行代碼是不值得的,它有點神祕。定義函數並調用它們。那就是人的思維是如何運作的。只需添加clearText();在你定義它之後,每個人都會知道發生了什麼。 – 2012-02-19 07:48:18

+0

哎呀,感謝您的幫助 – chintanparikh 2012-02-19 07:50:27

0

試圖把你函數中的document.ready即

$(document).ready(function(){ 
    // Your functions here... 
    $("input:text").each(function(e){ 
    // code goes here... 
    }); 
}); 

沒有必要把它包內的另一個大括號/()。

+0

對不起,我應該說,我上面發佈的是代碼片段,所有內容實際上都在$(document).ready – chintanparikh 2012-02-19 07:46:37

+0

我已經更新了答案。 – 2012-02-19 07:51:03