“我见过的大多数代码都采用占位符的值并将其填充到输入本身中,这导致了这个问题”
好吧,这几乎就是占位符文本在幕后所做的事情(尽管它并没有真正更新输入的值)。
一种选择是类似于以下内容:
http://fuelyourcoding.com/scripts/infield/ http://fuelyourcoding.com/scripts/infield/
这里的概念是使用 CSS 移动标签,使其位于字段顶部并且看起来像占位符文本。请注意,标签不一定与占位符文本相同。标签很重要,特别是对于可访问性而言,而占位符文本除了标签之外还可以被视为“帮助文本”。
另一个选项是您一直在做的事情,获取占位符属性的内容并通过 JS 将其移动到输入本身的值中。
您遇到的问题是您在检查虚假占位符文本是否仍然存在之前提交了表单。
为了解决这个问题,您希望将一个事件附加到表单的提交中,在提交表单之前,该事件将首先查看所有输入字段,获取它们的值,将其与其占位符属性进行比较,如果匹配,则设置值为空白。
UPDATE:
要解决您在与占位符文本匹配的用户输入值的注释中提出的问题,您可以执行以下操作:
$('input[placeholder]').each(function(){
if($(this).val() === $(this).attr('placeholder')){
// in the odd situation where the field is prepopulated with
// a value and the value just happens to match the placeholder,
// then we need to flag it
$(this).data('skipCompare','true');
}
// move the placeholder text into the field for the rest of the blank inputs
if($(this).val().length===0){
$(this).val($(this).attr('placeholder'))
}
// move the placeholder text into the field for the rest of the blank inputs
if($(this).val().length===0){
$(this).val() = $(this).attr('placeholder');
}
$(this)
.focus(function(){
// remove placeholder text on focus
if($(this).val()==$(this).attr('placeholder')){
$(this).val('')
}
})
.blur(function(){
// flag fields that the user edits
if( $(this).val().length>0 && $(this).val()==$(this).attr('placeholder')){
$(this).data('skipCompare','true');
}
if ( $(this).val().length==0){
// put the placeholder text back
$(this).val($(this).attr('placeholder'));
}
})
})
$('#submitButton').click(function(){
$('input[placeholder]').each(function(){
if( !($(this).data('skipCompare')) && $(this).val() == $(this).attr('placeholder') ){
$(this).val('');
};
alert($(this).val());
})
})
已经很晚了,我也累了,所以这一切可能是完全错误的。没有给出任何保证。 ;)