我正在尝试使用原型(prototype)创建 H2 标题,以便可以根据需要单独设置它们。
我正在使用 this.appendChild(document.createTextNode(''));
将文本添加到 H2
。我需要在 appendChild
之前使用父节点,我相信在这种情况下是 this
关键字,但我不确定它是否被识别为父节点或者它是否确实是 parent ?我也不确定如何通过构造函数本身的参数添加文本。我使用了一个变量“字体”,但不确定如何让它工作,因为它没有添加 css 样式?
我正在学习如何使用原型(prototype),所以如果我遗漏了任何其他明显的错误,请告诉我。
<div id='body'>
<div id='inner'>div here</div>
</div>
<script>
Heading.prototype.font;
Heading.prototype.color;
Heading.prototype.fontSize;
Heading.prototype.headingTxt;
Heading.prototype.setHeading = function() {
var inner = document.getElementById('inner');
this.headingTxt = document.createElement('h2');
this.headingTxt.font = this.appendChild(document.createTextNode(''));
this.headingTxt.style.color = this.color;
this.headingTxt.style.fontSize = this.fontSize;
inner.appendChild(headingTxt);
}
function Heading(font, color, fontSize) {
this.font = font;
this.color = color;
this.fontSize = fontSize;
}
var title = new Heading('heading here', 'red', 20);
title.setHeading();
</script>
谁能帮我解决这个问题?
最佳答案
这是我精简的工作版本:
function Heading(font, color, fontSize) {
this.font = font;
this.color = color;
this.fontSize = fontSize;
}
Heading.prototype.setHeading = function() {
var inner = document.getElementById('header'); //make sure inner exists
this.headingTxt = document.createElement('h2'); //you could also scope this to be local with var if you want it to be private
inner.appendChild(this.headingTxt);
}
var title = new Heading('heading here', 'red');
title.setHeading();
关于javascript - 使用原型(prototype)javascript设置标题样式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20689177/