2010/04/23

JavaScriptイベントハンドラ

サンプル
<html><body>
<script type="text/javascript">
function $(e) { return document.getElementById(e); }

function append_event(e, type, handler) {
if (e.addEventListener)
e.addEventListener(type, handler, false);
else
e.attachEvent('on' + type, handler);
}

function ChangeFGColor() {
$('para_msg').style['color'] = '#000099';
}

function ChangeBGColor() {
$('para_msg').style['backgroundColor'] = '#9999ff';
}

append_event(
window, 'load',
function () {
var e = $('btn_color');

append_event(e, 'click', ChangeBGColor);
append_event(e, 'click', ChangeFGColor);
}
);

</script>
<p id="para_msg">Hello, world!</p>
<form>
<input id="btn_color" type="button" value="change color">
</form>
</body></html>

ref http://d.hatena.ne.jp/dayflower/20080516/1210917670