javascript - Div 文本不显示

标签 javascript css html text

此代码旨在将元素元素显示为按钮上方 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/

相关文章:

html - 外部 CSS 文件无法获取类

html - 具有内联样式的 CSS 伪类

javascript - jQuery Live() 不起作用

Javascript 事件似乎没有添加到动态生成的文本框中

javascript - 检查数组中的每个项目在 JavaScript 中是否相同

javascript - 推送事件后来自 serviceWorker 的 PostMessage

asp.net - 如何在 ListItem 旁边放置一个按钮

javascript - 在 angularjs 中突出显示单击的超链接

html - 在另一个页面上重复页脚 html/css,但显示不同?

html - 图像存在但不显示为背景