2011-08-07 40 views
0

嘗試在文本位於頁面加載的輸入中的情況下嘗試使用自定義函數,以便將文本與文本在輸入中創建「信息」類似文本的其餘部分分組。我試過,​​,.bind('load'),.ready(),我沒有得到任何東西。只是看看是否有可能解決這一路上的碰撞問題。自定義函數上的textarea的jQuery加載事件

//removed some of the validation code for simplicity. 

/* 
to set a grey text infomation into a input field 
*/ 
$.fn.greyInfo = function (text) 
{ 

    //troubled code - start 
    $(this).load(function() 
    { 
     $(this).val(text); 
     $(this).css('color', 'grey'); 
    }); 
    //troubled code - end 

    $(this).blur(function() 
    { 
     if($(this).val() == "") 
     { 
      $(this).val(text); 
      $(this).css('color', 'grey'); 
     } 
    }); 

    $(this).focus(function() 
    { 
     if($(this).val() == text) 
     { 
      $(this).val(""); 
      $(this).css('color', 'black'); 
     } 
    }); 

} 
+0

發現我的回答 '$(本).blur();' 把這個在自定義函數 – thebtm

+0

結束時,我不認爲加載事件在這方面作爲觸發$(本)我認爲它已經在你的調用之前觸發,嘗試在你使用某個對象的函數後觸發它。 –

回答

2

答案很簡單,你不需要調用該函數加載,因爲它已經存在。

$.fn.greyInfo = function(text) 
{ 

// you also don't need to reference $(this) as the jquery object is implied 
     this.val(text); 
     this.css('color', 'grey'); 


    $(this).blur(function() 
    { 
     if($(this).val() == "") 
     { 
      $(this).val(text); 
      $(this).css('color', 'grey'); 
     } 
    }); 

    $(this).focus(function() 
    { 
     if($(this).val() == text) 
     { 
      $(this).val(""); 
      $(this).css('color', 'black'); 
     } 
    }); 

}; 
+0

我測試過了,它確實有效。 – rlemon

+0

非常感謝。 – thebtm