在页面首次加载

时间:2015-07-15 15:44:50

标签: javascript jquery html

我正在创建一个动态页面,其中包含几个div,当用户选择转到我页面上的下一段时,这些div会发生变化。但是,我无法让我的网站加载第一组信息。 HTML包含这些空白div,然后我的函数加载到JSON文件中并根据其ID更改div。当我第一次加载页面时,这些div显示没有文本。可能是因为首次加载页面时我的javascript没有运行?以下是我的HTML示例:

<div id="passage-section">
<!-- Title -->
<div id="passage-title"></div>
<!-- The panel that will display the content -->
<div id="passage"></div>
<!-- Button that when clicked activates a dialog box for the passage. -->
<button id="max-passage" class="max"></button>
</div>

这是我的功能:

//This section of code handles the calling of the first passage.  
//Loading in the JSON file and changing the contents of the page.
function loadFirstPassage()
{
    var timeout = 250;
    //load the new JSON file and change the elements
    $.getJSON("passages/2.1.1.json", function( data ) {
        document.getElementById("passage-title").innerHTML = data["passageNumber"];
        document.getElementById("passage").innerHTML = "<p class='serif'>".concat(data["reading"]).concat('</p>');\

        //fading the elements back in
        $("#passage-title").fadeIn(timeout);
        $("#passage").fadeIn(timeout);
   });
}

我试过在体内调用这个函数但是没有用,所以目前它被调用了。

<head>  
<!--The orginal load of the page   maybe it works, who knows? -->
<script>
$(window).load(function()
{
  loadFirstPassage();
});
</script>

2 个答案:

答案 0 :(得分:0)

尝试

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

而不是$(document).load

答案 1 :(得分:0)

你可以尝试在DOM完成后立即加载

(function() {
   console.log('DOM Loaded')
})();

jQuery会使用

$( document ).ready(function() {
    console.log('DOM Loaded');
});