javascript 如何在动态内容中创建动态内容

How to create dynamic content inside dynamic content in javascript

当我尝试对 div 中的动态加载执行 getelementbyid 时,我得到空值 我试过 window.onload = function () { 和 $(window).load(function() {

index.html:

<main >

    <div id="main-div">

    </div>

</main>

homepage.html:

<!-- categories Slider -->
<div class="container-fluid">
    <div class="site-slider-two px-md-4">
        <div class="row slider-two text-center" id="homepageCategories">

javascript:

function loadHomePage() {

    $("#main-div").load("homepage.html", function () {
}
}

function showCategoriesHomepage(categories) {

    window.onload = function () {

        homepageCategoriesId = document.getElementById(homepageCategories);

        homepageCategoriesId.innerHTML = "";

        //For loop that loops true all the categories
        for (var i = 0; i < messages.length; i++) {

            //Create dynamic li elements with child p elements
            var mainDiv = document.createElement('div');
            var span = document.createElement('span');
            var img = document.createElement('img');


            span.setAttribute("class", "border site-btn btn-span");

            img.setAttribute("src", categories.image);

            //Fills the p elements with user_id, description, created_at
            span.appendChild(document.createTextNode(categories.name));
            mainDiv.appendChild(img);
            mainDiv.appendChild(span);
}
}

主页加载后,我调用 api,完成后我尝试在 div 上获取元素,但它 returns null

更改此行...

homepageCategoriesId = document.getElementById(homepageCategories);

...对此

homepageCategoriesId = document.getElementById('homepageCategories');