当我尝试在div中动态加载时执行getelementbyid时,我得到null 我试过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上获取getelementbyid,但它返回null
答案 0 :(得分:1)
更改此行...
homepageCategoriesId = document.getElementById(homepageCategories);
...对此
homepageCategoriesId = document.getElementById('homepageCategories');