使用 Javascript 设置 HTML <span> 的内容
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4784568/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Set content of HTML <span> with Javascript
提问by Brian Beckett
In a webpage I am calling a WebService that gives me an integer value. I need to display this value in a block of text. I am currently using an HTML <span>
.
在一个网页中,我调用了一个 WebService,它给了我一个整数值。我需要在文本块中显示这个值。我目前正在使用 HTML <span>
。
So far, I've found two methods of putting my value in a span. innerText()
is an IE proprietary way of doing it and innerHTML()
is a non-standards compliant way, although widely supported.
到目前为止,我已经找到了两种将我的价值置于跨度中的方法。 innerText()
是一种 IE 专有的innerHTML()
方式,虽然得到广泛支持,但它是一种非标准兼容方式。
What is the correct standards compliant way of setting the text between <span>
and </span>
from Javascript?
在Javascript之间<span>
和</span>
从 Javascript设置文本的正确标准兼容方式是什么?
回答by user113716
This is standards compliant and cross-browser safe.
这是符合标准且跨浏览器安全的。
Example:http://jsfiddle.net/kv9pw/
示例:http : //jsfiddle.net/kv9pw/
var span = document.getElementById('someID');
while( span.firstChild ) {
span.removeChild( span.firstChild );
}
span.appendChild( document.createTextNode("some new content") );
回答by robinst
With modern browsers, you can set the textContent
property, see Node.textContent:
使用现代浏览器,您可以设置该textContent
属性,请参阅Node.textContent:
var span = document.getElementById("myspan");
span.textContent = "some text";
回答by Brian Donovan
To do it without using a JavaScript library such as jQuery, you'd do it like this:
要在不使用 JavaScript 库(例如 jQuery)的情况下执行此操作,您可以这样做:
var span = document.getElementById("myspan"),
text = document.createTextNode(''+intValue);
span.innerHTML = ''; // clear existing
span.appendChild(text);
If you do want to use jQuery, it's just this:
如果你确实想使用 jQuery,那就是这样:
$("#myspan").text(''+intValue);
回答by chaos
The Maximally Standards Compliant way to do it is to create a text node containing the text you want and append it to the span (removing any currently extant text nodes).
最大符合标准的方法是创建一个包含您想要的文本的文本节点并将其附加到跨度(删除任何当前存在的文本节点)。
The way I would actually do it is to use jQuery's .text()
.
我实际的做法是使用 jQuery 的.text()
.