Javascript – 找不到function?! 从onClick调用,函数在同一页面

我有一个非常奇怪和混乱的错误。

这是我的代码:

{if="$pjax === false"}{include="header"}{/if}  $(document).ready(function() { function clickclear(thisfield, defaulttext) { if (thisfield.value == defaulttext) { thisfield.value = ""; } } function clickrecall(thisfield, defaulttext) { if (thisfield.value == "") { thisfield.value = defaulttext; } } });  
  • Remember Me
Login {if="$pjax === false"}{include="footer"}{/if}

你可以看到有两个function, clickclearclickrecall 。 这些是从onClickonBlur上的表单输入调用的。 但是,当我运行它们时,我会收到以下javascript错误:

未捕获的ReferenceError:未定义clickclear

未捕获的ReferenceError:未定义clickrecall

有任何想法吗? 我知道它可能非常简单,但我看不到它。

这是因为你的函数在.ready()回调中。 这些在全球范围内是不可见的(这很好)。

最好使用jQuery的事件附件方法,如.on()

 $(document).ready(function(){ //your code function clickclear(){...} function clickrecall(){...} //the handlers $('#username').on('click',function(){ //bind click handler clickclear(this,'Username'); //things to do on click }).on('blur',function(){ //chain blur handler clickrecall(this,'Username'); //things to do on blur }); $('#password').on('click',function(){ //bind click handler clickclear(this,'Password'); //things to do on click }).on('blur',function(){ //chain blur handler clickrecall(this,'Password'); //things to do on blur }); ...other handlers... }); 

另外,Chrome还有一个placeholder属性,其作用类似于占位符文字: