最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

html - Alternative way to use JavaScript to write to a <div> element? - Stack Overflow

programmeradmin2浏览0评论

I want to print out a message in the page's <div> element upon page load. I have the following HTML and JavaScript code:

<body onload="printMsg()">
    <div id="write"></div>
</body>

function printMsg() {
    var node = document.getElementById("write");
    node.innerHTML = "<p>" + "Hello World!" + "</p>";
}

Here I used onload event in <body> element to call printMsg() upon page load.

But if I don't use onload event, is there any alternative way to write to <div id="write"></div> directly within the JavaScript function printMsg()?

I want to print out a message in the page's <div> element upon page load. I have the following HTML and JavaScript code:

<body onload="printMsg()">
    <div id="write"></div>
</body>

function printMsg() {
    var node = document.getElementById("write");
    node.innerHTML = "<p>" + "Hello World!" + "</p>";
}

Here I used onload event in <body> element to call printMsg() upon page load.

But if I don't use onload event, is there any alternative way to write to <div id="write"></div> directly within the JavaScript function printMsg()?

Share Improve this question asked Feb 27, 2013 at 18:46 tongatonga 12k25 gold badges78 silver badges96 bronze badges 2
  • 2 You can't write to a DOM element until it's loaded so you'd need some kind of callback equivalent to onload. If you want to avoid it you should be able to just make sure the script tag comes after the DOM element, I'd suggest right before the end of the body. You are writing to the div in the function...you can't invoke a function within it's declaration but you can do so immediately afterward function() {..}();. So try moving printMsg down and adding the (); after the closing brace. – Matt Whipple Commented Feb 27, 2013 at 18:51
  • Thanks Matt. It seems that I cannot put <div onload="printMsg()"></div> to invoke the function printMsg(). So besides the approaches pointed by others, is there any way to invoke the printMsg() function by adding a callback to <div> element? – tonga Commented Feb 27, 2013 at 19:18
Add a comment  | 

7 Answers 7

Reset to default 7

as Whipple suggested you can do it as following :

   <body>
    <div id="write"></div>
    <script>
    (function printMsg() {
        var node = document.getElementById("write");
        node.innerHTML = "<p>" + "Hello World!" + "</p>";
    })();
    </script>
    </body>        

DEMO

You can put these function inside the declaration: $(document).ready(function() { });

You can call these in you header inside 'script', or put it in another file and call it back. All the functions inside this declaration will run with the loading of the page. The effect is the same that you onload, but don't mess with your body tag.

You can write a simple javascript function to create an element instead of manually writing each tag, which can get confusing if you do it a lot.

Also, as Matt Whipple pointed out:

make sure the script tag comes after the DOM element

HTML:

<body>
    <div id="write"></div>
    <script>printMsg()</script>
</body>

Javascript:

function printMsg() {
    newElement = document.createElement('p');
    newElement.innerHTML = "Hello world!";
    document.getElementById("write").appendChild(newElement);
}

http://jsfiddle.net/Qrsmq/7/

You can use:

window.onload  =   function() {
    var node = document.getElementById("write");
    node.innerHTML = "<p>" + "Hello World!" + "</p>";
}

or

function printMsg() {
    newElement = document.createElement('p');
    newElement.innerHTML = "Hello world!";
    document.getElementById("write").appendChild(newElement);
}
document.body.onload = printMsg;

or

function printMsg() {
    newElement = document.createElement('p');
    newElement.innerHTML = "Hello world!";
    document.getElementById("write").appendChild(newElement);
}
window.onload  = printMsg;

There is also .ready function, but requires using jQuery. If you are already thinking of using jquery for other things this is the way to go. It runs once the DOM is ready.

But the most straight forward option would be to call the function inline, at the end of the body:

<body>
    <div id="write"></div>
    <script>
        (function(){ 
             //do something with #write
        });
    </script>
</body>

Like the ready function it also only waits for the DOM to be loaded, it ia faster than the onload listener and it should be as back compatible with browsers ad javascript is =)

var myWeb = new Object(), _m = "model", _v = "view", _c = "controller";

myWeb.model = {

    myEle   : "log",
    myText  : "Hello World!"

}
myWeb.view = {

    doText : function() {
        document.getElementById(myWeb[_m].myEle).innerHTML = myWeb[_m].myText;
    }

}
myWeb.controller = {

    init: function() {
        if (document.readyState == "complete") {
            this.run();
        } else {
            setTimeout(myWeb[_c].init, 11);
        }
    },
    run: function() {
        myWeb[_v].doText();
    }

}
myWeb[_c].init();

You can use the javascript plugin mustache JS, you render a template with a JSON notation and javascript. Minimal templating with {{mustaches}} in JavaScript. Allow you to use for a simple or complex template with a minimal code.

https://github.com/janl/mustache.js

Example of code:

// Json Data and Javascript function to calculate the value of return
var view = {
  title: "Joe",
  calc: function () {
    return 2 + 4;
  }
};

// The HTML Rendered with a simple example of template
var output = Mustache.render("{{title}} spends {{calc}}", view);

// Use your New HTML with native Javascript
document.getElementById("divWrite").innerHTML(output);

// Or you use your New HTML with JQuery
$("#divWrite").html(output);
发布评论

评论列表(0)

  1. 暂无评论