jQuery:仅显示新的JSON数据,使用自己的段落标记进行迭代 [英] jQuery: Display only new JSON data, iterated with its own paragraph tag

查看:78
本文介绍了jQuery:仅显示新的JSON数据,使用自己的段落标记进行迭代的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

仅显示JSON数据的新更新,使用jQuery / javascript在其自己的段落标记中与每个值项重复。

Display only new updates of JSON data, iterated with each value item in its own paragraph tag using jQuery/javascript.

如果数组中的每个项目 info 键内的已经在其自己的< p> 标记中输出; 继续循环,但等到有新项目。

If each item in the array inside the info key already is outputted in its own <p> tag; do not continue the loop but wait until there is a new item.

这是我的JSON:

{
  "info": [
    "Hello world,",
    "how are you doin?",
    "Its not going to well for me unfortunately."
  ]
}

使用这个jQuery脚本:

With this jQuery script:

function updatelog() {
 $.getJSON("/static/_info",
  function(data) {
   $.each(data, function(key, item) {
    var value = "";
    var i;
    for (i = 0; i < item.length; i++) {
     value += item[i];
     $("div").add('<p>' + value + '</p>').appendTo(document.body);
    }
   });
  });
}
var interval = window.setInterval(updatelog, 2000);

有了这个,我得到了所有的项目,但它不会停止迭代。我已经搜索了这个互联网,以至于我的输入密钥已经失去了救恩的全部希望。我想这很简单,但我是一个初学者,也不是一个javascript编码器,我准备脱掉我的头发。在此先感谢。

With this I get all the items but it doesn't stop iterating. I have searched the interwebs so much that my enter key has lost all hope for salvation. I guess this is pretty easy, but I'm a beginner and also not a javascript coder and i'm ready to pull my hair off. Thanks in advance.

推荐答案

您可以获取所有 p 元素的文字并将其推送到新数组,然后检查它是否包含来自对象的值

You could take text of all p elements and push it to new array and then check if it includes values from your object

var data = JSON.parse('{"info":["Hello world,","how are you doin?","Its not going to well for me unfortunately."]}'),
  pText = [];

$('p').each(function() {
  pText.push($(this).text());
});

data.info.forEach(function(el) {
  if (!pText.includes(el)) {
    $('body').append('<p>' + el + '</p>');
  }
})

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p>Hello world,</p>

这篇关于jQuery:仅显示新的JSON数据,使用自己的段落标记进行迭代的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆