为什么以下内容对我不起作用?
<script> document.getElementById('lbltipAddedComment').innerHTML = 'Your tip has been submitted!'; </script> <label id="lbltipAddedComment"></label>
因为您的脚本在运行之前运行,所以标签存在于页面中(在DOM中)。可以将脚本放在标签后,或者等待文档完全加载(使用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>