我有一个表单,其中的默认值提示用户输入数据。
这是我的表格。
<input type="text" id="name" name="name" class="input-text" value="Enter Name..." onfocus="if(this.value == 'Enter Name...') {this.value = '';}" onblur="if (this.value == '') {this.value = 'Enter Name...';}" />
<input type="text" id="email" name="email" class="input-text" value="Enter Email Address..." onfocus="if(this.value == 'Enter Email Address...') { this.value = '';}" onblur="if(this.value == '') { this.value ='Enter Email Address...';}"/>
<textarea name="message" id="message" class="input-textarea" onfocus="if(this.value == 'Enter your Message...') {this.value = '';}" onblur="if (this.value == '') {this.value = 'Enter your Message...';}">Enter your Message...</textarea>
这里有很多代码重复。我想将下面的代码转换为javascript函数。
onfocus="if(this.value == 'Enter Name...') {this.value = '';}" onblur="if (this.value == '') {this.value = 'Enter Name...';}"
我该怎么做?
最佳答案
您可以这样做,而不是包含任何“内联”代码:
function autoHideDefault(el) {
var defaultValue = el.value;
el.onblur = function() {
if(this.value == '') this.value = defaultValue ;
}
el.onfocus = function() {
if(this.value == defaultValue) this.value = '';
}
}
autoHideDefault(document.getElementById('name'));
autoHideDefault(document.getElementById('email'));
autoHideDefault(document.getElementById('message'));
关于javascript - 我如何将这段代码转换为javascript函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5139428/