2012-07-11 124 views
1

我想通過不同的動作提示不同的詞,但它不起作用。無法將參數傳遞給循環

這是我的代碼:

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

回答

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/