IE8 label update via javascript issue

2019-04-16 05:06发布

问题:

I am trying to use javascript to update the text in a html label.

It works in all browsers except IE8. In IE8 the label appears to be updated but is not displayed on the screen.

I've created demo code below that shows the issue.

Thanks

<html>
 <head>
 <script>
  function sendRequest() {               
    document.getElementById('errormessage').textContent="test";
    alert("textContent : "+document.getElementById('errormessage').textContent);
  }   
</script>

</head>

<body>

  <a href="javascript:void(0)" onclick="sendRequest();"> Click me</a>
   <br/>
  <label id="errormessage" style="color:#F00">&nbsp;</label>
</body> 
</html>

回答1:

IE 8 and under doesn't have textContent.

Try this:

function setText(el, text){
    if(typeof el.innerText !== 'undefined')
        el.innerText = text;
    else
        el.textContent = text;
}

function getText(el){
    return el.innerText || el.textContent;
}

function sendRequest() {
    var el = document.getElementById('errormessage');
    setText(el, "test");
    alert("textContent : "+getText(el));
}   


回答2:

document.getElementById('errormessage').innerHTML="test";