我有一个非常奇怪和混乱的错误.
这是我的代码:
- {if="$pjax === false"}{include="header"}{/if}
- <script type="text/javascript">
- $(document).ready(function() {
- function clickclear(thisfield,defaulttext) {
- if (thisfield.value == defaulttext) {
- thisfield.value = "";
- }
- }
- function clickrecall(thisfield,defaulttext) {
- if (thisfield.value == "") {
- thisfield.value = defaulttext;
- }
- }
- });
- </script>
- <form action='./login' method='post' name='form'>
- <ul class="form">
- <li><input type="text" name="username" value="Username" id="username" onclick="clickclear(this,'Username')" onblur="clickrecall(this,'Username')" /></li>
- <li><input type="password" name="password" value="Password" id="password" onclick="clickclear(this,'Password')" onblur="clickrecall(this,'Password')" /></li>
- <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>
- </ul>
- </form>
- <a href="javascript: form.submit()" class="button white">Login</a>
- {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():
- $(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','Password'); //things to do on click
- }).on('blur','Password'); //things to do on blur
- });
- ...other handlers...
- });
另外,Chrome还有一个占位符属性,其作用类似于占位符文字:
- <input type="text" placeholder="username" />
- <input type="password" placeholder="password" />