此代码旨在将元素元素显示为按钮上方 div 中的列表,但是,尽管按钮和提示有效,但 div 中没有显示文本。帮助!
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>Shopping List</title>
<style>
#button {
width:80px;
height:30px;
}
div.ex {
width:500;
height:500;
}
</style>
<script>
function a() {
var thing = prompt('Insert an item or press cancel');
if (thing != null && thing != undefined) {
document.getElementById('b') += thing;
}
else {
}
}
</script>
</head>
<body>
<div class='ex' style="color:#007AFC"></div>
<button onclick='a()' id='button'>Add Item</button>
</body>
</html>
最佳答案
首先,您正在使用 document.getElementById('b')
但是您没有带 id="b"
的 HTML 元素。其次,您不能仅使用 +=
运算符来更改元素的 HTML 内容。您需要像这样修改 innerHTML
属性:
document.getElementById('b').innerHTML += thing;
此外,您还需要一个带有 id="b"
的 HTML 元素,如下所示:
<div id="b" class='ex' style="color:#007AFC"></div>
但是,请考虑为 id
使用更具描述性的名称。
关于javascript - Div 文本不显示,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19594742/