Programing

JavaScript를 사용하여 레이블 텍스트 변경

lottogame 2020. 10. 14. 07:20
반응형

JavaScript를 사용하여 레이블 텍스트 변경


다음은 왜 저에게 효과가 없습니까?

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

레이블이 페이지 (DOM)에 존재하기 전에 스크립트가 실행되기 때문입니다. 레이블 뒤에 스크립트를 넣거나 문서가 완전히로드 될 때까지 기다리십시오 ( jQuery ready()또는 http://www.webreference.com/programming/javascript/onloads/ 와 같은 OnLoad 기능 사용 ).

작동하지 않습니다.

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

이것은 작동합니다 :

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

이 예제 (jsfiddle 링크) 는 순서 (스크립트 먼저, 그다음 레이블)를 유지하고 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>

.innerText또는 .value대신 시도 했습니까 .innerHTML?


스크립트가 실행될 때 레이블 요소가로드되지 않기 때문입니다. 레이블과 스크립트 요소를 바꾸면 작동합니다.

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

.textContent대신 사용하십시오 .

나는 이것을 시도 할 때까지 레이블의 가치를 바꾸는 데 어려움을 겪고 있었다.

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?


Using .innerText should work.

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

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


Try this:

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

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.

참고URL : https://stackoverflow.com/questions/4488714/change-label-text-using-javascript

반응형