【问题标题】:How do I call a JavaScript function's on loading my html page? [duplicate]如何在加载我的 html 页面时调用 JavaScript 函数? [复制]
【发布时间】:2018-08-10 15:33:57
【问题描述】:

我有一个页面,其中包含一些我想在页面加载时加载的函数。目前该函数仅在单击按钮时调用,我也希望在页面加载/刷新时加载此函数

function LOADMEONSTARTUP() {
    var reader = new XMLHttpRequest() || new ActiveXObject('MSXML2.XMLHTTP');
    reader.open('get', 'log.txt', true);
    reader.onreadystatechange = function () {
        if (reader.readyState == 4 && reader.status == 200) {
            displayContents1(reader.responseText);
        }
    };
    reader.send();
}

function displayContents1(content) {
    var wanted = 'apples';
    var words = content.split(/\s/);
    var found = [];
    words.forEach(function (word, index) {

        if (word === wanted && words[index + 1]) {
        found.push(words[index + 1]);
        }
    });
    console.log('found:', found);
    var el = document.getElementById('here1');
    el.innerHTML = found.length ? found.join('<br/>') : 'nothing found';
}

【问题讨论】:

标签: javascript html load


【解决方案1】:

我们可以通过向 body 添加一个 onload 函数来做到这一点

<body onload ="LOADMEONSTARTUP()">

这可以通过我们使用的Jquery来实现

$(document).ready(function(){
LOADMEONSTARTUP(); 
})

或者你可以参考这篇文章:

Pure JavaScript equivalent of jQuery's $.ready() - how to call a function when the page/DOM is ready for it

希望我能帮上忙 :)

【讨论】:

  • 两者都有效,但我有 20 个函数要加载 .. 所以它只加载其中 5 个函数,然后在页面加载时停止:(
  • 总是只加载 5 个函数吗?还是有所不同?如果是这样,您可能需要与您的上级检查您的项目的架构......如果它只有 5 个错误......它可能是一个语法错误。 javascript应该随时停止加载没有其他原因:)
  • 只有 5 个,就像你在网站加载后浏览到该网站然后停止
  • 这可能是一个语法错误,它正在避免执行整个代码。但是我不能确定,除非你向我展示这里使用的整个代码。
猜你喜欢
  • 2011-04-20
  • 1970-01-01
  • 1970-01-01
  • 2012-12-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-08-30
相关资源
最近更新 更多