首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >加载时未调用JavaScript函数

加载时未调用JavaScript函数
EN

Stack Overflow用户
提问于 2016-08-31 00:07:09
回答 2查看 64关注 0票数 1

我使用的是一个javascript函数,它应该在页面加载完成时调用(类似于JQuery的函数),如下所示:

代码语言:javascript
复制
<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;

}

当我在模型的赋值处设置断点时,我们正在命中它。但是,从来没有发生过任何其他事情(包括警告框。我不确定为什么它不能在加载时完全执行函数。

EN

回答 2

Stack Overflow用户

发布于 2016-08-31 00:16:47

这是可行的:

代码语言:javascript
复制
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");
});
票数 0
EN

Stack Overflow用户

发布于 2016-08-31 00:20:34

我建议你使用这个。

代码语言:javascript
复制
    (function () {
    var x = "Hello!!";      // I will invoke        myself
})();

匿名函数调用函数本身后的parantheses();。您可以像这样实现文档就绪事件。

代码语言:javascript
复制
    document.addEventListener('DOMContentLoaded', function() {
   // ...
});
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/39232338

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档