[英]Why is my class Paragraph not making a paragraph element <p>a</p> in JavaScript?
I have the following piece of code in JS:我在 JS 中有以下一段代码:
class Paragraph { constructor(text) { this.text = text; this.createParagraph(); } createParagraph() { var paragraph = document.createElement('p'); var p = paragraph.appendChild(document.createTextNode(this.text)); return p; } } var a = new Paragraph("a"); // <p>a</p> This is the result I want, which I'm not getting console.dir(a);
I want to be able to create what I've described above through var a = new Paragraph("a");我希望能够通过 var a = new Paragraph("a"); 创建我上面描述的内容。 but it isn't working, can anyone help out why?但它不起作用,有人可以帮助解释为什么吗?
There's two issues.有两个问题。 Firstly createParagraph()
needs to return the paragraph
, not p
as that contains the appended child element , in this case that's the text node.首先createParagraph()
需要返回paragraph
,而不是p
因为它包含附加的子元素,在这种情况下是文本节点。
Secondly the constructor needs to return the p
you created in createParagraph()
.其次,构造函数需要返回您在createParagraph()
创建的p
。 Try this:尝试这个:
class Paragraph { constructor(text) { this.text = text; return this.createParagraph(); } createParagraph() { var paragraph = document.createElement('p'); paragraph.appendChild(document.createTextNode(this.text)); return paragraph; } } var newPara = new Paragraph("Lorem ipsum"); document.body.appendChild(newPara); console.dir(newPara);
Change your function according to this solution:根据此解决方案更改您的功能:
createParagraph() {
const paragraph = document.createElement('p');
document.body.append(paragraph);
const p = paragraph.appendChild(document.createTextNode(this.text));
return p;
}
}
Also don't use var
.也不要使用var
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.