jQuery:仅显示新的JSON数据,使用自己的段落标记进行迭代
仅显示JSON数据的新更新,使用jQuery / javascript在其自己的段落标记中使用每个值项进行迭代。
如果info
键中数组中的每个项已经在其自己的
标记中输出; 不要继续循环,而是等到有新项目。
这是我的JSON:
{ "info": [ "Hello world,", "how are you doin?", "Its not going to well for me unfortunately." ] }
有了这个jQuery脚本:
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('' + value + '
').appendTo(document.body); } }); }); } var interval = window.setInterval(updatelog, 2000);
有了这个我得到了所有的项目,但它不会停止迭代。 我搜索了这个互联网,以至于我的输入键已经失去了救恩的全部希望。 我想这很简单,但我是一个初学者,也不是一个javascript编码器,我准备脱掉我的头发。 提前致谢。
您可以获取所有p
元素的文本并将其推送到新数组,然后检查它是否包含来自对象的值
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('' + el + '
'); } })
Hello world,
您可以从每个列表项生成哈希,并将其用作div元素中的id。 每次检索数据时,都要检查是否存在相应的ID。 如果它存在,那么该项目已经存在于您的页面中,因此您不必再次附加该项目。
function updatelog() { $.getJSON("/static/_info", function(data) { $.each(data, function(key, item) { var i; for (i = 0; i < item.length; i++) { var value = item[i]; var hashCode = value.hashCode(); if(!$("body").find("#" + hashCode).length){ $("div") .attr("id", hashCode) .add('' + value + '
') .appendTo(document.body); } } }); }); } var interval = window.setInterval(updatelog, 2000);
您可以将此实现用于hashCode
函数。 在Javascript / jQuery中从字符串生成哈希
String.prototype.hashCode = function() { var hash = 0, i, chr, len; if (this.length === 0) return hash; for (i = 0, len = this.length; i < len; i++) { chr = this.charCodeAt(i); hash = ((hash << 5) - hash) + chr; hash |= 0; // Convert to 32bit integer } return hash; };