【问题标题】:Add space/new line between elements with javascript使用javascript在元素之间添加空格/新行
【发布时间】:2016-10-25 08:00:58
【问题描述】:

所以我试图显示我的 Firebase 数据库中的所有问题和响应。它显示得很好,但看起来很难看,因为问题和回答之间没有空格。我尝试使用createElement 功能以及.innerHTML 添加不间断空格。没有任何工作。这是我到目前为止的代码:感谢您的帮助!

<button id="all" onclick="button()"> View All </button>
<h4> All Users: </h4>

<script>
    function button(){
        var userRef = new Firebase("https://speedpoll-1fd08.firebaseio.com");
        userRef.on("value", function(snapshot) {
            // The callback function will get called twice, once for "fred" and once for "barney"
            snapshot.forEach(function(childSnapshot) {
                // key will be "fred" the first time and "barney" the second time
                var key = console.log(childSnapshot.key());
                // childData will be the actual contents of the child
                // var userInfo = console.log(childSnapshot.val());
                var element = document.getElementById("viewAll");
                var para = document.createElement("h5");

                var node = document.createTextNode("Question: " + childSnapshot.key());
                console.log(childSnapshot.child("Option1").child('Response1').val());
                var node1= document.createTextNode("Response 1: " + childSnapshot.child("Option1").child('Response1').val());
                //var space = document.createElement("&nbsp;");
                element.innerHTML += "&nbsp;";
                var node2= document.createTextNode("Response 2: " + childSnapshot.child('Option2').child('Response2').val());
                var node3= document.createTextNode("Response 3: " + childSnapshot.child('Option3').child('Response3').val());
                para.appendChild(node);
                //para.appendChild(space);
                para.appendChild(node1);
                para.appendChild(node2);
                para.appendChild(node3);
                element.appendChild(para);

            });
        });

    }
</script>
<div id="viewAll">
</div>

【问题讨论】:

  • P.S.我有一个按钮,由于某种原因它不在粘贴的代码上
  • 你为什么不用一个简单的
    标签来创建一个空间呢?
  • 我如何在 javascript 中实现它?

标签: javascript html firebase firebase-realtime-database appendchild


【解决方案1】:

您可以通过添加 &lt;hr&gt; 元素来添加一行,如下所述:http://www.htmlgoodies.com/tutorials/getting_started/article.php/3479441

喜欢这个:


您还可以为每个元素添加 &lt;div&gt; 部分,并使用 CSS 设置边距、填充和边框的样式。 &lt;p&gt; 部分也是如此。

你可以玩弄这个 JSFiddle:

 http://jsfiddle.net/jmgomez/n0e1ev8e/

还可以查看如何使用 CSS 设置边框样式:http://www.w3schools.com/css/css_border.asp

【讨论】:

  • 这并没有真正的帮助。我很欣赏评论,但我知道如何使用 CSS。问题是使用 javascript 创建这些元素。这就是我需要使用的。
  • 唯一的问题是它会导致这样的打印:
  • 问题:你好吗?响应 1:好的响应 2:好。
  • 嗨塔拉斯,通常最好将问题分解为原子问题,因为您的问题说“它看起来很丑,因为问题和回答之间没有空格。”该问题的解决方案是在 HTML/CSS 域中。一旦看起来不错,第二步是使用 javascript 动态更改 DOM,通过您的代码,您似乎也知道如何做到这一点。很抱歉我回复晚了,我有一份工作,这是在“尽力而为”的基础上......