我想在不同的操作上提醒不同的单词,但它不起作用。
这是我的代码:
<input id=main value="ddddd">
<script type="text/javascript">
var obj = document.getElementById("main");
var items = [ "click", "keypress" ];
for ( var i = 0; i < items.length; i++ ) {
obj[ "on" + items[i] ] = function() {
alert( "Thanks for your " + items[i] );
};
}
</script>
答案 0 :(得分:3)
您需要创建一个闭包。这样的事情应该有效:
function makeClosure(eventName) {
return function() {
alert( "Thanks for your " + eventName );
};
}
var obj = document.getElementById("main");
var items = [ "click", "keypress" ];
for ( var i = 0; i < items.length; i++ ) {
obj[ "on" + items[i]] = makeClosure(items[i]);
}
jsFiddle:http://jsfiddle.net/NQKqk/