简体   繁体   English

加载时不调用JavaScript函数

[英]JavaScript function not being called upon load

I am using a javascript function that is supposed to invoke on page load complete (like JQuery's function) heres what it looks like: 我正在使用一个javascript函数,该函数应该在页面加载完成时调用(如JQuery的函数)继承人的样子:

<script>
var ready = function(fn) {

    // Sanity check
    if (typeof fn !== 'function') return;

    // If document is already loaded, run method
    if (document.readyState === 'complete') {
        return fn();
    }

    // Otherwise, wait until document is loaded
    // The document has finished loading and the document has been parsed but sub-resources such as images, 
    //stylesheets and frames are still loading. The state indicates that the DOMContentLoaded event has been fired.
    document.addEventListener('complete', fn, false);
};

ready(function() {
    alert(lang);
    Load(@Model.Language); //<--this is what I want called

    });
</script>

------->MVC Stuff<-------

 function Load(lang) {


 switch (lang) {
   case 'Other':
        BuildBox("text/text");
    case 'CSharp':
        BuildBox("text/x-csharp");
        break;

}

When I set the breakpoint at the Assignment from the model, we're hitting it. 当我在模型的Assignment中设置断点时,我们正在点击它。 However, nothing else ever happens (including the alert box. I'm not sure why it is not executing the function fully upon load. 然而,没有其他任何事情发生(包括警报框。我不知道为什么它没有在加载时完全执行该功能。

This works: 这有效:

function ready(fn) {

  // Sanity check
  if (typeof fn !== 'function') return;

  // If document is already loaded, run method
  if (document.readyState === 'complete') {
    fn();
  }

  // Otherwise, wait until document is loaded
  // The document has finished loading and the document has been parsed but sub-resources such as images, 
  //stylesheets and frames are still loading. The state indicates that the DOMContentLoaded event has been fired.
  document.addEventListener('readystatechange', function () {
    if (this.readyState === 'complete') fn();
  }, false);
}

ready(function() {
  alert("loading complete");
});

I suggest you to use this. 我建议你用这个。

    (function () {
    var x = "Hello!!";      // I will invoke        myself
})();

The parantheses(); parantheses(); after the anonymous function is calling the function itself. 在匿名函数调用函数本身之后。 And you can impliment document ready event like this. 你可以像这样恭维文件就绪事件。

    document.addEventListener('DOMContentLoaded', function() {
   // ...
});

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

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