JSON拆分 - 在间隔期间将数组文本放入li中

时间:2017-03-28 12:17:40

标签: javascript jquery arrays

我的任务是在jsonObj中获取3个不同的颜色列表并将它们放入<ul>。它们应该每次只出现一次,每秒一次。为了小提琴,我每隔5秒就把它放一次。

我还没有获得第二或第三个颜色列表,因为虽然我可以列出我的第一个颜色列表,但它们会在我为它们创建的listItem之外添加。它吐出的代码是:

&#13;
&#13;
var jsonObj = '{"one":["red","green","blue"], "two":["red","green","blue"], "three":["orange","purple","hotpink"]}',
  object = JSON.parse(jsonObj),
  cOne = object.one,
  cTwo = object.two,
  cThree = object.three,
  i = 0,
  timer;

$('body').append('<ul/>');

timer = setInterval(function() {

  $.each(cOne, function() {
    var list = $('body ul'),
      listItem = $(list).append('<li>'),
      html = $(listItem).append(cOne[i]);

    if (i < cOne.length) {
      i++;
      $(cOne[i]).split("");
      list.append(html);

    } else if (i = cOne.length) {
      i = 0;
    }

  });

}, 5 * 1000);

timer;
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
&#13;
&#13;
&#13;

也可在https://jsfiddle.net/ep76ba3u/

获取

它的作用:

<ul>
<li></li>
"red"
<li></li>
"blue"
</ul>

应该是什么样的:

<ul>
<li>red</li>
<li>blue</li>
</ul>

我试过重新整理一切。我尝试过使用wrap,innerWrap。我尝试过使用text()和其他一些方法。我开始在凌晨3点和现在凌晨5点开始工作......大脑被炒了。任何想法如何让这种感动都值得赞赏。

3 个答案:

答案 0 :(得分:1)

您无法附加部分HTML,这就是为什么$(list).append('<li>')会立即关闭<li>

您不应该在循环中修改标记。它令人讨厌且无能为力。

查看代码的这种方法:

&#13;
&#13;
var jsonObj = '{"one":["red","green","blue"], "two":["red","green","blue"], "three":["orange","purple","hotpink"]}',
  object = JSON.parse(jsonObj),
  iteration = 0,
  timer;

$('body').append('<div id=container>');

//a few utilities, because I don't want to repeat myself all over the place:
var string = value => value == null ? "" : String(value);
var wrapInNode = nodeName => value => `<${nodeName}>${ string(value) }</${nodeName}>`;

//here I create a few utility-methods that will build my markup:
var li = wrapInNode('li');
var ul = wrapInNode('ul');
var header = wrapInNode('h4');

timer = setInterval(function() {
  //building the complete markup and adding it at once
  var blocks = [],
    //how many rows should I show in this iteration
    numRowsLeft = ++iteration,
    //getting this result is just a nice sideeffect of using `every()` instead of `forEach()` 
    //to short-curcuit the loop
    done = Object.keys(object)
    .every(function(key) {
      //this line makes the title to be added with as a distinct iteration and not with the first item, 
      //check out what happens when you remove it
      --numRowsLeft;

      var rows = object[key]
        //shorten the Array to numRowsLeft, if necessary
        .slice(0, numRowsLeft)
        //wrap each item in a li-node with my predefined utility-function
        .map(li);

      numRowsLeft -= rows.length;

      //building the markup for this block
      blocks.push(header(key) + ul(rows.join("")));

      //here I'm short circuiting the loop. to stop processing the other keys on Object
      return numRowsLeft > 0;
    });

  $('#container').html(blocks.join(""));

  if (done) {
    clearInterval(timer);
  }
}, 1000);
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
&#13;
&#13;
&#13;

一直显示标题,只添加点数:

&#13;
&#13;
var jsonObj = '{"one":["red","green","blue"], "two":["red","green","blue"], "three":["orange","purple","hotpink"]}',
  object = JSON.parse(jsonObj),
  iteration = 0,
  timer;

$('body').append('<div id=container>');

var string = value => value == null ? "" : String(value);
var wrapInNode = nodeName => value => `<${nodeName}>${ string(value) }</${nodeName}>`;
var li = wrapInNode('li');
var ul = wrapInNode('ul');
var header = wrapInNode('h4');

timer = setInterval(function() {
  var numRowsLeft = ++iteration,
    blocks = Object.keys(object)
    .map(function(key) {
      var rows = object[key]
        .slice(0, numRowsLeft)
        .map(li);

      numRowsLeft -= rows.length;
      return markup = header(key) + ul(rows.join(""));
    });

  $('#container').html(blocks.join(""));

  // If I'd had room to show even more rows, then I' done
  if (numRowsLeft > 0) {
    clearInterval(timer);
  }
}, 1000);
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
&#13;
&#13;
&#13;

答案 1 :(得分:0)

var jsonObj = '{"one":["red","green","blue"], "two":["red","green","blue"], "three":["orange","purple","hotpink"]}',
    object = JSON.parse(jsonObj),
cOne = object.one,
cTwo = object.two,
cThree = object.three,
i = 0,
timer;

$('body').append('<ul>');
var i = 0;
timer = setInterval(function() {
    if (i === cOne.length - 1) clearInterval(timer);

    $('body ul').append('<li>');
    $('body ul li').last().text(cOne[i]);
    i++;
}, 1000);

答案 2 :(得分:0)

我觉得有必要提出一个答案,该答案应该通过缓存jQuery对象来表现更好,并处理对象及其中的每种颜色,为每种颜色点击DOM一次。

var jsonObj = '{"one":["red","green","blue"], "two":["red","cyan","darkblue"], "three":["orange","purple","hotpink"]}',
  objects = JSON.parse(jsonObj);

// set timer values
var basetime = 1000;
var delaytime = basetime;
// cache the ul list
var myul = $('<ul/>').appendTo('body');
//process outer objects
$.each(objects, function(key, item) {
  // process color array held in item
  $.each(item, function(index, color) {
    setTimeout(function() {
      $('<li/>').text(color).css('color', color).appendTo(myul);
    }, delaytime);
    delaytime = delaytime + basetime;
  });
});

在此处测试https://jsfiddle.net/MarkSchultheiss/yb1w3o73/