1

I want to alert different word base on different actions, but it doesn't work.

this is my code:

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

1 回答 1

3

You need to create a closure. Something like that should work:

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/

于 2012-07-11T03:42:49.990 回答