以下是 html 文件中的代码。将 JavaScript 代码 (if (this.value etc etc)
) 从 html 文件中分离出来的理想方法是什么?
input type="text" name="username" onblur="if (this.value == '') {this.value = 'email';}" onfocus="if (this.value == 'email') {this.value = '';}"
最佳答案
<head>
<script type="text/javascript">
function ClearDefValue (input) {
if (input.value == '') {
input.value = input.defaultValue;
}
}
function SetDefValue (input) {
if (input.value == input.defaultValue) {
input.value = '';
}
}
</script>
</head>
<body>
<input type="text" name="username" value="email" onblur="ClearDefValue (this)" onfocus="SetDefValue (this)" />
</body>
如果您想将 JavaScript 内容放入外部文件:
HTML 文件:
<head>
<script type="text/javascript" src="utils.js"></script>
</head>
<body>
<input type="text" name="username" value="email" onblur="ClearDefValue (this)" onfocus="SetDefValue (this)" />
</body>
utils.js 文件:
function ClearDefValue (input) {
if (input.value == '') {
input.value = input.defaultValue;
}
}
function SetDefValue (input) {
if (input.value == input.defaultValue) {
input.value = '';
}
}
相关链接:
script element ,
onblur event ,
onfocus event .
关于javascript - 输入类型 : Separating JavaScript Code From Front End Code,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3513894/