【问题标题】:How to insert text in an HTML document using JavaScript?如何使用 JavaScript 在 HTML 文档中插入文本?
【发布时间】:2013-05-28 13:49:25
【问题描述】:

我想用字符串 "saying" 替换 span 元素为 id "randMsg"。这是我现在拥有的:

 document.getElementById('randMsg').write(saying);

有什么想法吗?我是 JavaScript 菜鸟,我做错了什么?

【问题讨论】:

  • .write() 是使用错误的函数。试试document.getElementById('...').innerHTML = ...
  • 我假设你想设置跨度的文本。试试这个document.getElementById('randMsg').innerHTML("saying");
  • 重复? innerHTML without the html, just text(我认为这个问题与获取值有关,而不是设置它。)
  • @PSL 您将 DOM 与 jQuery 混淆了。你的意思是$('#randMsg').innerHTML("saying"); 还是类似的?

标签: javascript html random


【解决方案1】:

您可以使用textContent 属性来更新元素内的文本:

document.getElementById("randMsg").textContent = "Replaced Content";

http://jsfiddle.net/RaGng/

或者如果你需要它在IE8及以下工作,你可以检测对textContent的支持,如果不支持,你可以使用非标准的innerText来代替:

var el = document.getElementById("randMsg"),
    msg = "Replaced Content";

("textContent" in el) ? el.textContent = msg : el.innerText = msg;

http://jsfiddle.net/RaGng/4/

【讨论】:

【解决方案2】:

以下W3C DOM code适用于所有主流浏览器,包括IE8及更早版本。

var node = document.getElementById('randMsg');
var textToUse = 'Hello, World!';

// Remove all the children of the node.
while (node.hasChildNodes()) {
    node.removeChild(node.firstChild);
}

// Now add the text.
node.appendChild(document.createTextNode(textToUse));

Working JsFiddle here.

您也可以使用innerText,但 Firefox 不支持:

node.innerText = textToUse;

或者,您可以使用textContent,但是,IE 版本 8 和旧版不支持:

node.textContent = textToUse;

Quirksmode 对以上所有内容都维护得非常好browser compatibility tables

【讨论】:

    【解决方案3】:

    Working jsFiddle Demo

    您必须设置元素的innerHTML 属性。考虑以下标记:

    <span id="randMsg"></span>
    

    在你的 JS 代码中:

    var saying = 'Say Hello World';
    document.getElementById('randMsg').innerHTML = saying;
    

    你的结果是:

    <span id="randMsg">Say Hello World</span>
    

    注意

    别忘了在你的元素之后添加这个脚本(或等待 DOM 准备好):

    <body>
        <span id="randMsg"></span>
        <script>
            var saying = 'Say Hello World';
            document.getElementById('randMsg').innerHTML = saying;
        </script>
    </body>
    

    【讨论】:

    • 如果文本包含&lt;&amp; 等字符,innerHTML 可能无法正常工作。听起来你想要innerText,它将接受字符串作为文本,但当然缺少 Firefox 支持。
    猜你喜欢
    • 2018-01-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-05-15
    • 2023-04-06
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多