如何正确地控制或对表单字段焦点上的占位符执行某些操作
How do I correctly control or do something to placeholder on focus of a forms field?
我有一个包含3个字段的注册表单:
用户名
电子邮件
密码
在大多数浏览器上,当用户单击某个特定字段时,显示的占位符值会被清空,这样用户就可以键入,如果用户什么都不键入,则占位符文本会重新出现。无论如何,有些浏览器(例如chrome)不会隐藏占位符文本onfocus,所以我不得不编写一些javascript来处理这一问题。
我对javascript还很陌生,但对我来说,我为处理这一问题而编写的代码似乎并不正确。我觉得它可以更短更好。
对于每个字段,我都有一个文档准备功能:
$("#field_id").focusin(function() {
$(this)[0].placeholder = "";
});
$("#field_id").focusout(function() {
$(this)[0].placeholder = "Enter email";
});
我的html:
<p><input class="signupFields" data-validate="true" id="user_username" name="user[username]" placeholder="Username" size="30" type="text" /></p>
<p><input class="signupFields" data-validate="true" id="user_email" name="user[email]" placeholder="Email" size="30" type="text" /> </p>
<p><input class="signupFields" data-validate="true" id="user_password" name="user[password]" placeholder="Password" size="30" type="password" /> </p>
所以想象一下,乘以3。。对于这样一个简单的需求,似乎有很多代码。此外,我真的不喜欢我试图模仿javascripts document.getElementById的事实。我必须有一种方法可以用更像jQuery的方式来做到这一点。不喜欢[0]。
有谁能给我举一个更干净的例子来做同样的事情吗?
亲切问候
我建议您不必担心这一点,但为了删除焦点上的占位符文本(并恢复blur
上的placeholder
),我建议如下:
$('input').focus(
function(){
$(this).data('placeholder',this.placeholder).removeAttr('placeholder');
}).blur(
function(){
$(this).attr('placeholder',$(this).data('placeholder')).data('placeholder','');
});
JS Fiddle演示。
使用$(this)[0]
表示法的唯一原因是从jQuery化的$(this)
对象"突破"回本机DOM节点。为了避免这样做,只使用this
:更容易
$('input').focus(
function(){
this.dataPlaceholder = this.placeholder;
this.removeAttribute('placeholder');
}).blur(
function(){
this.placeholder = this.dataPlaceholder;
this.removeAttribute('dataPlaceholder');
});
JS Fiddle演示。
参考文献:
blur()
(jQuery)focus()
(jQuery)data()
(jQuery)focus()
(jQuery)removeAttr()
(jQuery)- CCD_ 11
假设您的html如下:
<input id="username" type="text" placeholder="username"/>
<input id="email" type="text" placeholder="email"/>
<input id="password" type="text" placeholder="password"/>
你的JS可能是:
$("input").focusin(function() {
$(this).data('placeholder',this.placeholder);//store the current placeholder
this.placeholder = "";//no need for $(this)[0]
}).focusout(function() {
this.placeholder = $(this).data('placeholder');//retrieve the stored placeholder
});
这将仅用一位代码来针对所有这些代码。
下面是一个演示:http://jsfiddle.net/JKirchartz/SGZNQ/
相关文章:
- 使用javascript的Asp.net内容占位符
- Internet Explorer缺少占位符支持,特别是密码字段
- 如何隐藏按钮单击事件上的占位符
- 需要URL模板占位符查找和替换功能的输入
- 初始化ng模型时,Angular ui选择占位符不起作用
- 如何在ie7或更高版本中设置密码字段的占位符
- 在不使用javascript的情况下,可以在表单字段中设置文本占位符(以提示最终用户插入特定格式)
- Select2-使用自定义模板时不显示占位符
- 替换字符串中的占位符值
- 为什么我应该使用HTML5(上下文:占位符)
- 在contentEditable元素中居中占位符插入符号
- 从气球弹出窗口中删除占位符
- 选择“选项”时更改输入的占位符
- 错误:ReCAPTCHA占位符元素必须为空
- 如何更改文本区域的颜色's文本,具体取决于它是否为占位符
- 得到一个没有属性的错误“;占位符”;在xhtml strict 1.0中
- 使用Node/Javascript提取字符串中的所有占位符
- 更改 html 输入字段中的占位符属性
- 当用户在输入字段事件中输入内容时,为该字段事件添加动画占位符
- 如何正确地控制或对表单字段焦点上的占位符执行某些操作