迭代文本节点以创建中断

时间:2017-04-03 22:40:30

标签: javascript html css arrays

我在迭代文本节点以创建中断时遇到了麻烦。

        var i;
        var args = ['Once upon a time', 'there were three bears',
                           'and a little girl named goldilocks.'];

        for (i = 0; i < args.length; i++) {
            var legendText2 = document.createTextNode(args[i]);
            var legendTextEl2 = document.createElement('p');
            legendTextEl2.setAttribute('class', 'legendPara');
            legendTextEl2.appendChild(legendText2);
            legendTextEl2.appendChild(document.createElement('br'));
            }

出于某种原因,代码只返回数组中的最后一项,然后返回&#39; br&#39;而不是返回每个项目的&#39; br&#39;介于&#39;之间。我不确定我在逻辑上弄得一团糟。有什么想法吗?

3 个答案:

答案 0 :(得分:1)

这是因为你不断重新创建legendTextEl2,但只有最后一个存在。尝试在for循环结束时添加此行:

document.body.appendChild(legendTextEl2)

var i;
var out = document.getElementsByClassName('legendPara');
var args = ['Once upon a time', 'there were three bears',
  'and a little girl named goldilocks.'
];

for (i = 0; i < args.length; i++) {
  var legendText2 = document.createTextNode(args[i]);
  var legendTextEl2 = document.createElement('p');
  legendTextEl2.setAttribute('class', 'legendPara');
  legendTextEl2.appendChild(legendText2);
  legendTextEl2.appendChild(document.createElement('br'));
  document.body.appendChild(legendTextEl2); <-- added missing semi-colon
}

答案 1 :(得分:0)

您在每个循环上覆盖legendTextEl2变量。我修改了你的代码。这对我有用。

    var i;
            var out = document.getElementsByClassName('legendPara');
            var args = ['Once upon a time', 'there were three bears',
                               'and a little girl named goldilocks.'];

            var legendTextEl2;
            var currentDiv = document.getElementById("div1");   

            for (i = 0; i < args.length; i++) {

                var legendText2 = document.createTextNode(args[i]);
                legendTextEl2 = document.createElement('p');
                legendTextEl2.setAttribute('class', 'legendPara');
                legendTextEl2.appendChild(legendText2);
                legendTextEl2.appendChild(document.createElement('br'));

                document.body.insertBefore(legendTextEl2, currentDiv);
            }

答案 2 :(得分:0)

        var i;
        legendTextEl2 = document.createElement('p');
        var args = ['stuff', 'more stuff', 'read this'];
        for (i = 0; i < args.length; i++) {
            legendText2 = document.createTextNode(args[i]);
            legendTextEl2.setAttribute('class', 'legendPara');
            legendTextEl2.appendChild(legendText2);
            legendTextEl2.appendChild(document.createElement('br'));
            }

我得到了这个工作:)