使用 JQuery 和 JavaScript for 循环进行文本提示
我正在开发一个小应用程序,要求用户输入一些信息。 我想在输入字段中显示文本提示。 我在 for 循环中执行此操作... 加载页面时,提示显示正确,但“焦点”和“模糊”事件没有任何反应...
我想知道为什么当我不在 js 代码中使用“for 循环”时,一切正常找到...
顺便说一句,我使用 for 循环的原因是因为我不想重复遵循“DRY”原则...
感谢您的帮助!
LP
这是代码:
<script src="/javascripts/jquery.js" type="text/javascript"></script>
<script type="text/javascript">
var form_elements = ['#submission_url', '#submission_email', '#submission_twitter']
var text_hints = ['Website Address', 'Email Address', 'Twitter Username (optional)']
$(document).ready(function(){
for(i=0; i<3; i++) {
$(form_elements[i]).val(text_hints[i]);
$(form_elements[i]).focus(function(i){
if ($(this).val() == text_hints[i]) {
$(this).val('');
}
});
$(form_elements[i]).blur(function(i){
if ($(this).val() != text_hints[i]) {
$(this).val(text_hints[i]);
}
});
}
});
</script>
I'm developing a small app where i ask users to put some info.
I want to show text hints in the input fields.
I do this in a for loop...
When the page is loaded, the hints are displayed correctly but nothing happens on 'focus' and 'blur' events...
I'm wondering why since when I don't use a 'for loop' in my js code, everything works find...
By the way the reason I use a for loop is because I don't want to repeat myself following 'DRY' principles...
Thx for your help!
LP
Here's the code:
<script src="/javascripts/jquery.js" type="text/javascript"></script>
<script type="text/javascript">
var form_elements = ['#submission_url', '#submission_email', '#submission_twitter']
var text_hints = ['Website Address', 'Email Address', 'Twitter Username (optional)']
$(document).ready(function(){
for(i=0; i<3; i++) {
$(form_elements[i]).val(text_hints[i]);
$(form_elements[i]).focus(function(i){
if ($(this).val() == text_hints[i]) {
$(this).val('');
}
});
$(form_elements[i]).blur(function(i){
if ($(this).val() != text_hints[i]) {
$(this).val(text_hints[i]);
}
});
}
});
</script>
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我不久前做过这个。它会做你想做的事情,
你只需使用它,就像
它通过读取初始值来加水印一样。
所以将你的输入设置为
I did this a while ago. it will do what you want
you simply use it like
it will watermark by reading the initial value.
so set your input like
伙计们!我在那里写的脚本不是我打算发布的脚本......
不管怎样,我写了另一个脚本来完美地处理我想要完成的事情。
这里是!
干杯!
Guys! the script I wrote up there is not the one I intended to post...
Anyway, I wrote another script that handles what I wanted to accomplish perfectly.
Here it is!
Cheers!