简体   繁体   English

页面加载时调用函数

[英]Function getting called on the load of page

for (var key in obj[i]) {
    dataDump[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) . 要点是调用function(zeKey){...}(key) When you do so, key, which is a string is copied as a parameter (zeKey) to your anonymous function. 这样做时,会将作为字符串的键key作为参数(zeKey)复制到您的匿名函数中。

The following 下列

var callback = function(zeKey){
    return function(e){
        dataDump[zeKey] = e.source.value;
    }; 
}(key);
  1. Calls the anonymous function with argument zeKey . 使用参数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. 如果1表示“正在调用该函数”,则这是预期的行为。

This entire code should be called only after DOM is ready. 仅在DOM准备好后才应调用整个代码。 Place all these in a function and make sure the function is called only on window.onload or (jQuery's) .ready() 将所有这些放置在一个函数中,并确保仅在window.onload或(jQuery的.ready()上调用该函数

The function returned by the function will be called only during the callback. 该函数返回的函数仅在回调期间被调用。

Add these code once dom is created. 创建dom后添加这些代码。 If above code is inside a function, attach to window.load or write these code at the end of page. 如果以上代码在函数内,请附加到window.load或在页面末尾编写这些代码。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM