使用 jQuery 的 .live/.bind 影响 for 循环创建的输入
我有两个数组,一个包含输入名称,另一个包含为每个输入提供的值。有 7 个输入,因此我创建了一个循环来填充每个输入的值,然后进行设置,以便当该输入获得焦点时文本将消失,如果未输入任何内容,则恢复原始值文本。这可以通过 jQuery 循环来完成吗?在我看来 .live 和 .bind 不适用于此目的。我是否必须在每个输入事件焦点和模糊事件中进行硬核?
for (var i=0;i<7;i++) {
$('#user_' + input_names[i]).attr('value', default_values[i]);
$('#user_' + input_names[i]).live("blur", function(){
if(this.value == '')this.value=default_values[i];
});
$('#user_' + input_names[i]).live("focus", function(){
if(this.value == default_values[i])this.value='';
});
}
此处更新,按照 Eric 的要求释放数组:
var input_names = ['username', 'password'];
var default_values = ['Username', 'Password'];
for (var i=0;i<2;i++) {
$('#user_' + input_names[i]).attr('value', default_values[i]);
$('#user_' + input_names[i]).blur(function(){
if(this.value == '')this.value=default_values[i];
});
$('#user_' + input_names[i]).focus(function(){
if(this.value == default_values[i])this.value='';
});
}
I have two arrays, one with input names, and one with the value to give each input. There are 7 inputs, so I made a loop to fill out each input with it's value, then make it so that the text will disappear when that input is focused, and restore the original value text if nothing was typed. Is this possible to do through a loop with jQuery? It seems to me .live and .bind won't work for this purpose. Will I have to hardcore in each input event focus&blur event?
for (var i=0;i<7;i++) {
$('#user_' + input_names[i]).attr('value', default_values[i]);
$('#user_' + input_names[i]).live("blur", function(){
if(this.value == '')this.value=default_values[i];
});
$('#user_' + input_names[i]).live("focus", function(){
if(this.value == default_values[i])this.value='';
});
}
Update here, releasing the arrays as Eric requested:
var input_names = ['username', 'password'];
var default_values = ['Username', 'Password'];
for (var i=0;i<2;i++) {
$('#user_' + input_names[i]).attr('value', default_values[i]);
$('#user_' + input_names[i]).blur(function(){
if(this.value == '')this.value=default_values[i];
});
$('#user_' + input_names[i]).focus(function(){
if(this.value == default_values[i])this.value='';
});
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您似乎正在寻找 HTML5
placeholder
属性。只需将 HTML 更改为:如果您想要向后兼容,有一个 jQuery 插件 。引用插件后,只需这样做:
至于你的初始代码有什么问题,我怀疑存在闭包问题,并且
i
保留了 7 的值。你最好重写它,就像这:Looks like you're looking for the HTML5
placeholder
attribute. Just change your HTML to this:If you want backwards compatibility, there's a jQuery plugin for that. With the plugin referenced, just do this:
As for what's wrong with your initial code, I suspect there's a closure problem, and
i
is retaining the value of 7. You'd do better to rewrite it like this: