简体   繁体   English

页面加载Javascript之前无法添加到DOM内容

[英]Can't add to DOM content before page load Javascript

I am currently trying to add a bunch of elements to a list using javscript after querying from parse. 我目前正在尝试从解析后使用javscript将一堆元素添加到列表中。

I am able to get the full list if I don't add any click listeners, however if I do add click listeners, only the first 5 items appear in the list. 如果我不添加任何点击侦听器,则可以获取完整列表,但是如果我添加点击侦听器,则列表中仅出现前5个项目。

Here is the code in my javascript file, it is called first in the html: 这是我的javascript文件中的代码,它在html中首先被调用:

if (!Parse.User.current()){
    window.location.href = 'index.html';
}
else {
    getParticipants();
}

$( document ).ready(function() {


$('#sign-out').click(function(){
    Parse.User.logOut();
    window.location.href = 'index.html';
    });

}); });

function getParticipants (){
var Participants = Parse.Object.extend("Participants");
var query = new Parse.Query(Participants);
query.ascending("patientID");
query.find({
    success: function(results) {
        for (var i = 0; i < results.length; i++) {
            var object = results[i];
            var id = object.get("patientID");
            $(".list-group").append("<li class='list-group-item' id='" + id + "'>" + id + "</li>");
            (function (id) {
                $('#' + object.get("patientID")).click(function (e) {
                    e.preventDefault();

                    if (typeof(Storage) !== "undefined") {
                        localStorage.setItem("patientID", id);
                    } else {
                        // Sorry! No Web Storage support..
                    }

                    window.location = 'profile.html';
                });
            }(id));
        }
    },
    error: function(error) {
        alert("Error: " + error.code + " " + error.message);
    }
});

} }

You can never modify the DOM before the page loads because at that point the DOM isn't ready. 在页面加载之前,您永远不能修改DOM,因为那时DOM还没有准备好。

Any DOM manipulation should be done after onload event is fired. 触发onload事件后,应执行任何DOM操作。

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

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