【问题标题】:Setting button title in HTML to a non-formatted text将 HTML 中的按钮标题设置为非格式化文本
【发布时间】:2014-05-21 01:52:16
【问题描述】:

我有一个简单的 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>

明确地说,我希望标题为 &lt;strong&gt;my text&lt;/strong&gt; 而不是我的文字

那么在按钮内显示非格式化文本的正确方法是什么?

【问题讨论】:

    标签: javascript html button text


    【解决方案1】:

    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,可以替代使用。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-07-26
      • 1970-01-01
      • 1970-01-01
      • 2019-01-05
      • 1970-01-01
      • 2015-02-10
      • 2011-12-09
      • 2018-10-28
      相关资源
      最近更新 更多