我正在嘗試使用原型創建H2標題,以便可以根據需要單獨設置它們。我使用this.appendChild(document.createTextNode(''));
將文本添加到H2
。我需要使用appendChild
之前的父節點,我認爲這種情況下是this
關鍵字,但我不確定它是否被識別爲父級或者它是否實際上是父級?我也不確定如何通過構造函數本身的參數添加文本。我已經使用了一個變量「字體」,但不知道如何使它工作,因爲它不添加CSS樣式?使用原型javascript設置標題樣式
我正在學習如何使用原型,所以如果有任何其他明顯的錯誤,我錯過了,請讓我知道。
<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>
任何人都可以幫我解決這個問題嗎?
哪個父節點? 'this'是指'Heading'的一個實例,即'title',而不是DOM元素。 –
明確使用'this'是錯誤的。我希望它引用作爲父項創建的'H2'元素,以便文本節點將成爲子項。 – moonshineOutlaw