[英]Changing the text of a Label in javascript doesn't work
I am trying to change the text of a Label using javascript like this in an aspx page 我试图在aspx页面中使用像这样的javascript来更改标签的文本
document.getElementById('DetailSection_EssLabel1').Text = "Revised Date";
But when I am in the debugging mode on IE by using F12 button, this is what I see for the field, 但是当我通过使用F12按钮进入IE的调试模式时,这就是我在该字段中看到的内容,
<SPAN class=FormFieldHeader id=DetailSection_EssLabel1 Text="Revised Date">Assigned Completion Date</SPAN>
Though the text is changed to Revised Date, it is still showing Assigned Completion Date in the front end. 尽管文本已更改为“修订日期”,但仍在前端显示“分配的完成日期”。 Can someone tell me what I am missing. 有人可以告诉我我想念的东西吗? Thanks 谢谢
If you want to set a label's text, you'd better use textContent
property, like this: 如果要设置标签的文本,则最好使用textContent
属性,如下所示:
document.getElementById('DetailSection_EssLabel1').textContent = "Revised Date";
innerText
is not a standard property and you'll definitely get an issue in FireFox innerText
不是标准属性,您肯定会在FireFox中遇到问题
Native Javascript objects do not have a text
property, but they do have innerHTML
and innerText
properties. 本机Javascript对象没有text
属性,但是它们具有innerHTML
和innerText
属性。 To change the text of an element, you can use either: 要更改元素的文本,可以使用以下任一方法:
document.getElementById('DetailSection_EssLabel1').innerHTML = "Revised Date";
. 。
or document.getElementById('DetailSection_EssLabel1').innerText = "Revised Date";
或document.getElementById('DetailSection_EssLabel1').innerText = "Revised Date";
. 。
使用内文
document.getElementById('DetailSection_EssLabel1').innerText="Revised Date";
Neither innerText
nor textContent
are cross-browser compatible if you include IE 8 and older. 如果包含IE 8和更早的版本,则innerText
和textContent
都不与跨浏览器兼容。
Using the jQuery text
method is typically the easy button. 使用jQuery text
方法通常是简单的按钮。
if jQuery is not an option, the most compatible way with pure DOM is to use text nodes, for example: 如果没有jQuery,则与纯DOM最兼容的方式是使用文本节点,例如:
var outputDiv = document.getElementById('DetailSection_EssLabel1');
var childNodes = outputDiv.childNodes;
// nodeType == 3 is a text node
if (!(childNodes.length == 1 && childNodes[0].nodeType == 3)) {
outputDiv.innerHTML = ''; // one way to clear any existing content
outputDiv.appendChild(document.createTextNode(''));
}
outputDiv.childNodes[0].nodeValue = 'Revised Text';
Fiddle: https://jsfiddle.net/4m0wpjdo/1/ 小提琴: https : //jsfiddle.net/4m0wpjdo/1/
EDIT: I also wanted to mention that using innerHTML
to inject text is really not a good idea. 编辑:我也想提一下,使用innerHTML
注入文本确实不是一个好主意。 It's all too easy to forget to escape special characters when using this approach. 使用这种方法时,很容易忘记转义特殊字符。 This opens you up to incorrect display of the text at best and XSS attacks at worst (if user-supplied text is included). 这可以使您最好地显示错误的文本,而在最坏的情况下则受到XSS攻击(如果包括用户提供的文本)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.