通过 JavaScript 动态创建和打印 h1 标签

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/28929786/
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-10-28 09:46:57  来源:igfitidea点击:

Dynamically create and print h1 tags through JavaScript

javascripthtml

提问by crank123

I need to be able to create a function in JavaScript where all I need to do is type h1("hello") and it will print hello.

我需要能够在 JavaScript 中创建一个函数,我需要做的就是输入 h1("hello") 并且它会打印 hello。

I want to avoid this method:

我想避免这种方法:

function h1(text) {
    document.write('<h1>'+text+'</h1>');
}

This is what I have:

这就是我所拥有的:

function h1(text) {
    var div = document.createElement('div');
    document.appendChild(div);
    var h1 = document.createElement('h1');
    div.appendChild(h1);
    h1.createTextNode(text);
}

回答by Vladu Ionut

<script>
function myFunction(text) {
    var h = document.createElement("H1");
    var t = document.createTextNode(text);
    h.appendChild(t);
    document.body.appendChild(h);
}
</script>

回答by T.J. Crowder

You don't need the div, and you need to append to document.body, not document. Also, elements don't have a createTextNode, that's a method on document:

您不需要div,并且需要附加到document.body,而不是document。此外,元素没有createTextNode,这是一种方法document

function h1(text) {
    var h1 = document.createElement('h1');
    h1.appendChild(document.createTextNode(text));
    document.body.appendChild(h1);
}

Live example:

现场示例:

function h1(text) {
    var h1 = document.createElement('h1');
    h1.appendChild(document.createTextNode(text));
    document.body.appendChild(h1);
}
var counter = 0;
var timer = setInterval(function() {
  ++counter;
  h1("Hi #" + counter);
  if (counter == 5) {
    clearInterval(timer);
  }
}, 500);

More to explore:

更多探索: