简体   繁体   中英

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.

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.

Here is the code in my javascript file, it is called first in the 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.

Any DOM manipulation should be done after onload event is fired.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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