使用 JavaScript 更改标签文本

为什么下面这些对我不起作用?

<script>
document.getElementById('lbltipAddedComment').innerHTML = 'Your tip has been submitted!';
</script>
<label id="lbltipAddedComment"></label>
715116 次浏览

Because your script runs BEFORE the label exists on the page (in the DOM). Either put the script after the label, or wait until the document has fully loaded (use an OnLoad function, such as the jQuery ready() or http://www.webreference.com/programming/javascript/onloads/)

This won't work:

<script>
document.getElementById('lbltipAddedComment').innerHTML = 'your tip has been submitted!';
</script>
<label id="lbltipAddedComment">test</label>

This will work:

<label id="lbltipAddedComment">test</label>
<script>
document.getElementById('lbltipAddedComment').innerHTML = 'your tip has been submitted!';
</script>

This example (jsfiddle link) maintains the order (script first, then label) and uses an onLoad:

<label id="lbltipAddedComment">test</label>
<script>
function addLoadEvent(func) {
var oldonload = window.onload;
if (typeof window.onload != 'function') {
window.onload = func;
} else {
window.onload = function() {
if (oldonload) {
oldonload();
}
func();
}
}
}


addLoadEvent(function() {
document.getElementById('lbltipAddedComment').innerHTML = 'your tip has been submitted!';


});
</script>

Because a label element is not loaded when a script is executed. Swap the label and script elements, and it will work:

<label id="lbltipAddedComment"></label>
<script>
document.getElementById('lbltipAddedComment').innerHTML = 'Your tip has been submitted!';
</script>

Have you tried .innerText or .value instead of .innerHTML?

Because the script will get executed first.. When the script will get executed, at that time controls are not getting loaded. So after loading controls you write a script.

It will work.

Using .innerText should work.

document.getElementById('lbltipAddedComment').innerText = 'your tip has been submitted!';

Use .textContent instead.

I was struggling with changing the value of a label as well, until I tried this.

If this doesn't solve try inspecting the object to see what properties you can set by logging it to the console with console.dir as shown on this question: How can I log an HTML element as a JavaScript object?

Try this:

<label id="lbltipAddedComment"></label>
<script type="text/javascript">
document.getElementById('<%= lbltipAddedComment.ClientID %>').innerHTML = 'your tip has been submitted!';
</script>

Here is another way to change the text of a label using jQuery:

<script>
$("#lbltipAddedComment").text("your tip has been submitted!");
</script>

Check the JsFiddle example