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

前端之家收集整理的这篇文章主要介绍了jquery – Javascript – 找不到功能?!从onClick调用,函数在同一页面前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我有一个非常奇怪和混乱的错误.

这是我的代码

  1. {if="$pjax === false"}{include="header"}{/if}
  2. <script type="text/javascript">
  3. $(document).ready(function() {
  4. function clickclear(thisfield,defaulttext) {
  5. if (thisfield.value == defaulttext) {
  6. thisfield.value = "";
  7. }
  8. }
  9. function clickrecall(thisfield,defaulttext) {
  10. if (thisfield.value == "") {
  11. thisfield.value = defaulttext;
  12. }
  13. }
  14. });
  15. </script>
  16. <form action='./login' method='post' name='form'>
  17. <ul class="form">
  18. <li><input type="text" name="username" value="Username" id="username" onclick="clickclear(this,'Username')" onblur="clickrecall(this,'Username')" /></li>
  19. <li><input type="password" name="password" value="Password" id="password" onclick="clickclear(this,'Password')" onblur="clickrecall(this,'Password')" /></li>
  20. <li><span style='display:block;height:27px;float:left;line-height:27px;'>Remember Me</span> <div id='itoggle' style='float:right;'><input type="checkBox" id="remember" class='itoggle' /></div><div class='clearfix'></div></li>
  21. </ul>
  22. </form>
  23. <a href="javascript: form.submit()" class="button white">Login</a>
  24. {if="$pjax === false"}{include="footer"}{/if}

你可以看到有两个功能,clickclear和clickrecall.这些是从onClick和onBlur上的表单输入调用的.但是,当我运行它们时,我会收到以下javascript错误

Uncaught ReferenceError: clickclear is not defined

Uncaught ReferenceError: clickrecall is not defined

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

解决方法

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

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

  1. $(document).ready(function(){
  2.  
  3. //your code
  4. function clickclear(){...}
  5. function clickrecall(){...}
  6.  
  7. //the handlers
  8. $('#username').on('click',function(){ //bind click handler
  9. clickclear(this,'Username'); //things to do on click
  10. }).on('blur',function(){ //chain blur handler
  11. clickrecall(this,'Username'); //things to do on blur
  12. });
  13.  
  14. $('#password').on('click','Password'); //things to do on click
  15. }).on('blur','Password'); //things to do on blur
  16. });
  17.  
  18. ...other handlers...
  19.  
  20. });

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

  1. <input type="text" placeholder="username" />
  2. <input type="password" placeholder="password" />

猜你在找的jQuery相关文章