我正在使用一个 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;
}
当我在模型的分配处设置断点时,我们就命中了它。但是,没有发生任何其他事情(包括警报框。我不确定为什么它在加载时没有完全执行该函数。
最佳答案
这有效:
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");
});
关于加载时未调用 JavaScript 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39232338/