简体   繁体   中英

Generate HTML with JavaScript not working?

I'm quite new to JavaScript so I don't understand what's not working. The Code:

var postCount = 0;

function generatePost(title, time, text) {
    var div = document.createElement("div");
    div.className = "content";
    div.id = "post_" + postCount;
    document.getElementById("postcontainer").appendChild(div);

    var h3 = document.createElement("h3");
    div.id = "post_h3_" + postCount;
    h3.innerHTML = title;
    document.getElementById("post_" + postCount).appendChild(div);

    var span = document.createElement("span");
    document.getElementById("post_h3_" + postCount).appendChild(div);
    span.innerHTML = time;

    var paragraphs[] = text.split("||");
    for (var p : paragraphs[] {
        var paragraphCount = 0;
        var h3 = document.createElement("h3");
        document.getElementById("post_p_" + postCount + "_" + paragraphCount).appendChild(div);
        paragraphCount++;
    }
    postCount++;
}

function loadPosts() {
    generatePost("Testing Title", "I don't know", "This is || a paragraph");
}

I included it with:

<body onload="loadPosts()">

In the end, nothing shows up. Not even in the Inspector in my Browser. Is my Code even run? Did I forget an essential doStuffNow()?

Second: If I add a class to a div with JavaScript, do the CSS-Rules in the style.css append to it?

是的,要回答问题的第二部分, 是的 ,将将应用于类的CSS样式添加到添加了相同类的对象。

You have errors in your code. What editor do you use? You can also use browser console to check for errors in your page. Check here:

var paragraphs = text.split("||");
for (var p in paragraphs) {
    /*
    *
    * Where do you use your var p?
    *
    */
    var paragraphCount = 0;
    var h3 = document.createElement("h3");
    document.getElementById("post_p_" + postCount + "_" + paragraphCount).appendChild(div);
    paragraphCount++;
}

Why don't you try with jQuery?

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