我不明白为什么单击按钮后它不显示文本?有什么我想念的吗?
HTML:
<button id="myBtn" onClick="myFunction()">Try it</button>
JAVASCRIPT:
document.getElementById("myBtn").addEventListener("click", myFunction);
function myFunction(){
"use strict";
var newpara = document.createElement("p");
var newcontent = document.createTextNode("This is a paragraph.");
}
答案 0 :(得分:1)
您需要在文档中附加newpara
元素,以便使其在网页上显示。另外,您应该将创建的文本节点添加到段落元素中
请考虑以下内容:
function myFunction(){
"use strict";
var newpara = document.createElement("p");
var newcontent = document.createTextNode("This is a paragraph.");
// [ADD] Ensure that content is added to the paragraph element
newpara.appendChild(newcontent);
// [ADD] Ensure the paragraph element is added to the document
document.body.appendChild(newpara);
}