gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 21:41:35 27 4
gpt4 key购买 nike

当我尝试在 div 中动态加载时执行 getelementbyid 时,我得到 null我尝试了 window.onload = function () { 和 $(window).load(function() {

index.html:

<main >

<div id="main-div">

</div>

</main>

主页.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 上获取elementbyid,但它返回 null

最佳答案

更改此行...

homepageCategoriesId = document.getElementById(homepageCategories);

...到此

homepageCategoriesId = document.getElementById('homepageCategories');

关于javascript - 如何在javascript中的动态内容中创建动态内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60355164/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com