phi*_*owe 81 html javascript label innerhtml
为什么以下不适合我?
<script>
document.getElementById('lbltipAddedComment').innerHTML = 'Your tip has been submitted!';
</script>
<label id="lbltipAddedComment"></label>
Run Code Online (Sandbox Code Playgroud)
Kon*_*rak 121
因为您的脚本在页面上存在标签之前运行(在DOM中).将脚本放在标签之后,或者等到文档完全加载(使用OnLoad函数,例如jQuery ready()
或http://www.webreference.com/programming/javascript/onloads/)
这不起作用:
<script>
document.getElementById('lbltipAddedComment').innerHTML = 'your tip has been submitted!';
</script>
<label id="lbltipAddedComment">test</label>
Run Code Online (Sandbox Code Playgroud)
这将有效:
<label id="lbltipAddedComment">test</label>
<script>
document.getElementById('lbltipAddedComment').innerHTML = 'your tip has been submitted!';
</script>
Run Code Online (Sandbox Code Playgroud)
这个例子(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>
Run Code Online (Sandbox Code Playgroud)
mvl*_*dic 16
因为执行脚本时未加载标签元素.交换标签和脚本元素,它将工作:
<label id="lbltipAddedComment"></label>
<script>
document.getElementById('lbltipAddedComment').innerHTML = 'Your tip has been submitted!';
</script>
Run Code Online (Sandbox Code Playgroud)
请.textContent
改用.
我也在努力改变标签的价值,直到我尝试了这一点.
如果这没有解决,请尝试检查对象以查看可以通过将其登录到控制台来设置哪些属性console.dir
,如此问题所示:如何将HTML元素记录为JavaScript对象?
小智 8
使用.innerText
应该工作.
document.getElementById('lbltipAddedComment').innerText = 'your tip has been submitted!';
Run Code Online (Sandbox Code Playgroud)
这是使用 jQuery 更改标签文本的另一种方法:
<script>
$("#lbltipAddedComment").text("your tip has been submitted!");
</script>
Run Code Online (Sandbox Code Playgroud)