Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
176 views
in Technique[技术] by (71.8m points)

javascript - 使用JavaScript更改标签文本(Change label text using JavaScript)

Why doesn't the following work for me?

(为什么以下不适合我?)

<script>
    document.getElementById('lbltipAddedComment').innerHTML = 'Your tip has been submitted!';
</script>
<label id="lbltipAddedComment"></label>
  ask by phil crowe translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Because your script runs BEFORE the label exists on the page (in the DOM).

(因为您的脚本在页面上存在标签之前运行(在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/ )

(将脚本放在标签之后,或者等到文档完全加载(使用OnLoad函数,例如jQuery ready()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:

(这个例子(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>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...