当我尝试在 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/