Html 使用 JavaScript 写入 <div> 元素的替代方法?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15119856/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-29 05:57:09  来源:igfitidea点击:

Alternative way to use JavaScript to write to a <div> element?

javascripthtml

提问by tonga

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

我想<div>在页面加载时在页面元素中打印一条消息。我有以下 HTML 和 JavaScript 代码:

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

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

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

在这里,我onload<body>元素中使用事件来调用printMsg()页面加载。

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

但是如果我不使用onload事件,有没有其他方法可以<div id="write"></div>直接在 JavaScript 函数中写入printMsg()

回答by Behnam Esmaili

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

演示

回答by madaaah

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

您可以将这些函数放在声明中: $(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.

您可以在“脚本”中的标题中调用它们,或者将其放在另一个文件中并调用它。此声明中的所有函数都将随着页面加载而运行。效果与您加载相同,但不要弄乱您的正文标签。

回答by Joey

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.

您可以编写一个简单的 javascript 函数来创建一个元素,而不是手动编写每个标签,如果您这样做很多,这可能会让人感到困惑。

Also, as Matt Whipple pointed out:

此外,正如马特惠普尔指出的那样:

make sure the script tag comes after the DOM element

确保脚本标签在 DOM 元素之后

HTML:

HTML:

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

Javascript:

Javascript:

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

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

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

回答by Rafael Marcos

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;

回答by Martin Turjak

There is also .readyfunction, 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.

也有.ready函数,但需要使用jQuery。如果您已经在考虑将 jquery 用于其他事情,那么这就是您要走的路。一旦 DOM 准备就绪,它就会运行。

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

但最直接的选择是在 的末尾调用内联函数body

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

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

就像ready函数一样,它也只等待加载 DOM,它比onload侦听器快,并且应该与浏览器兼容,javascript 是 =)

回答by Bny

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();

回答by Rafael Marcos

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.

您可以使用 javascript 插件 mustache JS,您可以使用 JSON 表示法和 javascript 呈现模板。在 JavaScript 中使用 {{mustaches}} 进行最小模板化。允许您以最少的代码用于简单或复杂的模板。

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

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);