2014-04-08 27 views
-10

我有一個簡單的html頁面設置按鈕標題非格式化文本

<body> 
 
<button type="button" id="button1" onclick="foo()">Result!</button> 
 
    <script type="text/javascript"> 
 
    function foo() { 
 
    var button = document.getElementById("button1"); 
 
    } 
 
    </script> 
 
</body>

我想改變點擊按鈕標題。
標題可能包含HTML標記,我希望它能夠按原樣呈現(無格式)。

我試過this後建議的方式,它適用於普通文本。不幸的是格式化的HTML標籤和不存在非格式化文本:

<body> 
 
<button type="button" id="button1" onclick="foo()">Result!</button> 
 
    <script type="text/javascript"> 
 
    function foo() { 
 
    var button = document.getElementById("button1"); 
 
    button.innerHTML = "<strong>my text</strong>" 
 
    } 
 
    </script> 
 
</body>

要清楚,我想要的標題是<strong>my text</strong>,而不是我的文字

那麼什麼是在按鈕內呈現非格式文本的正確方法?

回答

4

的innerText屬性將做的工作:

<body> 
 
<button type="button" id="button1" onclick="foo()">Result!</button> 
 
    <script type="text/javascript"> 
 
    function foo() { 
 
    var button = document.getElementById("button1"); 
 
    button.innerText = "<strong>my text</strong>" 
 
    } 
 
    </script> 
 
</body>

注: Firefox不支持的innerText,但有自己的屬性稱爲的textContent,它可以代替使用。