如何重构这个代码块使其变得简单且动态?
$(document).ready(function() {
$('.watermark').focus(function() {
if (this.className == 'watermark')
{
this.className = '';
this.value = '';
}
});
$('.watermark').blur(function() {
if (this.value == '')
{
this.className = 'watermark';
this.value = 'Type here';
}
});
});
我有这段代码,它工作完美,只是它不是动态的。我想知道是否有一种优雅的方法可以动态地将值重置为原始值。我在想,也许如果您在其 ID 或某种其他类型的属性中定义了原始文本,您可以通过这种方式重置它..或者您可以使用变量、数组或元组。 SO认为最好的方法是什么?
$(document).ready(function() {
$('.watermark').focus(function() {
if (this.className == 'watermark')
{
this.className = '';
this.value = '';
}
});
$('.watermark').blur(function() {
if (this.value == '')
{
this.className = 'watermark';
this.value = 'Type here';
}
});
});
I have this block of code that works perfectly except that it is not dynamic. I was wondering if there was an elegant way to reset the value to the original dynamically. I was thinking that maybe if you defined the original text in its ID or some other sort of attribute you could reset it that way.. or maybe you could use variables or arrays or tuples. What does SO think is the best way of doing it?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
将值存储到输入的其他属性中怎么样?
How about storing the value into some other attribute of the input?
在这种情况下,我更喜欢使用 html5(占位符属性 ) 与 javascript 回退。
该脚本将检测本机占位符是否可用,如果不可用,它将从占位符属性中获取文本并对其进行模拟。
In this scenario i prefer to use html5(placeholder attrinute) with javascript fall back.
This script will detect if native placeholder is available if not it will take text from placeholder attribute and simulate it.
如果它的作用域为每个元素,您可以将其存储在变量中:
You can just store it in a variable if it's scoped to each element: