开发者

Function getting called on the load of page

for (var key in obj[i]) {
    dataDum开发者_如何学Pythonp[key] = textField.value;
    var callback = function(zeKey){
       return function(e){
          dataDump[zeKey] = e.source.value;
       }; 
    }(key);
    textField.addEventListener('change', callback);
}

When I load the window, this function gets called automatically, which I don't want and instead I want this to be called only when I do a change.

The main point is calling function(zeKey){...}(key). When you do so, key, which is a string is copied as a parameter (zeKey) to your anonymous function.


The following

var callback = function(zeKey){
    return function(e){
        dataDump[zeKey] = e.source.value;
    }; 
}(key);
  1. Calls the anonymous function with argument zeKey.
  2. This anonymous function returns another function. This returned function is assigned to the callback.

If 1 what you mean by "the function is getting called" then this is expected behavior.

This entire code should be called only after DOM is ready. Place all these in a function and make sure the function is called only on window.onload or (jQuery's) .ready()

The function returned by the function will be called only during the callback.


Add these code once dom is created. If above code is inside a function, attach to window.load or write these code at the end of page.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜