以下是html文件中的代碼。什麼是理想的方式來分離JavaScript代碼(如果(this.value等)等)從HTML文件?輸入類型:從前端代碼分離代碼
input type="text" name="username" onblur="if (this.value == '') {this.value = 'email';}" onfocus="if (this.value == 'email') {this.value = '';}"
以下是html文件中的代碼。什麼是理想的方式來分離JavaScript代碼(如果(this.value等)等)從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。
<!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
廢話,只要把你的腳本放在end body標籤之前,如果它是一個相當簡單的網站。
<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,如果您有兩個字段,它會是什麼樣子? – thesimpledesigner 2010-08-18 16:04:26
'document.getElementsByTagName('input')'和一個for循環。本應該首先告訴我這件事:( – 2010-08-18 16:06:33
將這項工作: 的window.onload =函數(){ \t VAR輸入= document.getElementsByTagName( '輸入'); \t \t爲(VAR K = 0; k
thesimpledesigner
2010-08-18 16:22:48