以下是html文件中的代码。从html文件中分离javascript代码(if(this.value etc etc))的理想方法是什么?
input type="text" name="username" onblur="if (this.value == '') {this.value = 'email';}" onfocus="if (this.value == 'email') {this.value = '';}"
答案 0 :(得分:1)
<!doctype html>
<html><head>
<script src="file.js"></script></head><body>
<input id="foo" type="text">
</body></html>
方法#1:
您在<head>
中使用<script>
引用的file.js中的:
window.onload = function() {
var input = document.getElementById('foo');
input.onfocus = function() { if ( this.value == '' ) { this.value = 'blah';} }
input.onblur = function() { if ( this.value == 'blah') { this.value = ''; } }
}
理想情况下,您需要使用支持dom侦听器的addEvent函数。
方法#2:
(可以说)更优雅的方式是:
var addEvent = (function() {
function addEventIE(el, ev, fn) {
return el.attachEvent('on' + ev, function(e) {
return fn.call(el, e);
});
}
function addEventW3C(el, ev, fn) {
return el.addEventListener(ev, fn, false);
}
return window.addEventListener ? addEventW3C:addEventIE;
})();
addEvent(window, 'load', function() {
var input = document.getElementById('foo');
addEvent(input, 'blur', function(){});
addEvent(input, 'focus', function(){});
});
方法#3:
您还可以避免整个onload
和addEvent
废话,如果它是一个相当简单的网站,只需将您的脚本放在最终正文标记之前。
<script src="file.js"></script>
</body>
file.js:
var input = document.getElementById('foo');
input.onfocus = function() { if ( this.value == '' ) { this.value = 'blah';} }
input.onblur = function() { if ( this.value == 'blah') { this.value = ''; } }
答案 1 :(得分:1)
<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