我的脚本不起作用,我只是想更改 div 元素中的文本
这是我的 JavaScript 代码
var jumbo = document.getElementsByClassName("jumbotron");
var button = document.getElementById("changebg")
function changeBackground(){
document.getElementsByClassName("jumbotron").innerHTML = "BLASAKLSJL";
}
这是我的 html 代码:
<div class="jumbotron">
<button id="changebg" onclick="changeBackground()">
CLICK ME
</button>
</div>
最佳答案
<强> document.getElementsByClassName()
将返回一组对象,您需要指定要更新的对象。
示例:
document.getElementsByClassName("jumbotron")[index].innerHTML = "BLASAKLSJL";
____________________________________________^^^^^^^
如果只有 一个元素 具有 jumbotron
类,那么您可以使用 [0] :
document.getElementsByClassName("jumbotron")[0].innerHTML = "BLASAKLSJL";
如果有多个元素,那么您应该循环遍历它们:
var elements = document.getElementsByClassName("jumbotron");
for(var i=0;i<elements.length;i++){
elements[i].innerHTML = "new html here";
}
希望这有帮助。
关于javascript - 我的 JavaScript 只能工作,不能改变文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39899774/