2017-04-06 26 views
2

我將在其上顯示一些消息,其中包含一些樣式。 例如:'<span style="color: rgb(255, 0, 0);">Hello</span>',如何在Javascript中使頁面減速

我該如何將它聲明爲javascript變量,以便將我的文本設置在需要的位置。

我是這樣設置的。 this.header.setHtml("Hello");這工作正常,但我想把一些cls。如何實現這一點。

+0

'示例setHtml'請分享這個的實施。 – gurvinder372

+0

這是在extJS http://docs.sencha.com/extjs/6.0.0/modern/Ext.Label.html#method-setHtml – David

回答

4

也許你想

var spanEle = '<span style="color: rgb(255, 0, 0);">Hello</span>'; 
this.header.setHtml(spanEle); 
+0

完全一樣的方式,我試過了,但我錯過的是我正在使用「 「, 喜歡這個。 'this.header.setHtml(「spanEle」);' – David

+1

@David是的。請不要使用「」。當你使用「」時,腳本認爲它是一個字符串而不是變量 –

+0

是的。請記住。 – David

1

假設你的頭是

<h1 id="header"></h1> 

然後設置HTML應該是那樣簡單

document.getElementById("header").innerHTML = '<span style="color: rgb(255, 0, 0);">Hello</span>'; 

所有你需要做的是找出如何到達該特定元素

例如,如果報頭元件是

<span class="header"></span> 

然後使它

document.querySelector(".header").innerHTML = '<span style="color: rgb(255, 0, 0);">Hello</span>'; 
2

這裏是用幾個不同的方法

function appendMessage(text){ 
 
    document.getElementById('message').append(text); 
 
} 
 

 
appendMessage('Hello '); 
 
appendMessage('world'); 
 

 

 
function appendHtml(html){ 
 
    document.getElementById('output1').innerHTML += html; 
 
} 
 

 
appendHtml('<span class="green">Hello </span>'); 
 
appendHtml('<span class="red">World </span>'); 
 

 
function setHtml(value){ 
 
    document.getElementById('output2').innerHTML =value; 
 
} 
 

 
setHtml('<span class="green">Hello </span>'); 
 
setHtml('<span class="red">World </span>'); 
 

 
//then if you would like you can use prototype to extend Element to add setHtml 
 
Element.prototype.setHtml = function(html){ 
 
    this.innerHTML = html; 
 
} 
 

 
//you can then use it like this 
 
document.getElementById('prototype_example').setHtml('<span class=red>This works too!</span>');
#message, .red{ 
 
    color: rgb(255, 0, 0); 
 
} 
 

 
.green{ 
 
    color: rgb(0,188, 50); 
 
}
<span id=message></span> 
 
<br /> 
 
<span id=output1></span> 
 
<br /> 
 
<div id=output2></div> 
 
<br/> 
 
<div id="prototype_example"></div>