无法将参数传递给循环

时间:2012-07-11 03:35:54

标签: javascript loops scope

我想在不同的操作上提醒不同的单词,但它不起作用。

这是我的代码:

<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>

1 个答案:

答案 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/