我知道以前也有人问过类似的问题here和 here 。但这些并不完全类似于我的情况,因为他们试图更改输入框的值,而我试图更新 div
的 HTML元素。我的问题是,我正在 HTML 页面顶部调用 JS 函数,该函数旨在更新 innerHTML
div
之一页面上的元素。由于某种原因,这不起作用。根据this question的回答,我知道这可能是因为我什至在页面完全加载之前就尝试访问 div。为了解决这个问题,我尝试从主题 div 的 onload()
调用该函数。事件。然而,即使这样也行不通。
function wotd() {
$('#wotd').HTML("<strong>test</strong>");
alert($('#wotd').text());
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script>
//wotd();
</script>
<div class="col col-md-4">
<!-- WOTD panel -->
<div class="panel panel-default panel-box card-effect">
<div class="panel-heading panel-title">Word of the Day</div>
<div id="wotd" class="panel-body panel-text" onload="wotd();">
Word of the day not currently available.
</div>
</div>
</div>
最佳答案
innerHTML
是 javasript
属性。您应该使用jquery
中的html()
来替换元素的内容。而且 div
没有 onload
事件。您应该在文档准备就绪
或正文加载
上执行此操作,如下所示。
function wotd() {
$('#wotd').html("<strong>test</strong>");
alert($('#wotd').text());
}
wotd();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="col col-md-4">
<div class="panel panel-default panel-box card-effect">
<div class="panel-heading panel-title">Word of the Day</div>
<div id="wotd" class="panel-body panel-text" onload="wotd();">
Word of the day not currently available.
</div>
</div>
</div>
关于javascript - InnerHTML 不工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34363007/