在每个函数的特定结果之后插入元素

Insert elements after certain results in each function

本文关键字:结果 之后 插入 元素 函数      更新时间:2023-09-26

请看看这个小提琴

是否有办法在第二个循环中插入link - google.com之后的<h3>text</h3>color - Black之后的<h3>sss</h3>元素?

我希望结果是这样的:

title - A
link - google.com
<h3>text</h3>
image - image.com
price - $1295.00
brand - ABC
color - Black
<h3>sss</h3>
material - Rubber
以下是json文件和代码: JSON:

[
  {
    "title": "A",
    "link": "google.com",
    "image": "image.com",
    "price": "$1295.00",
    "brand": "ABC",
    "color": "Black",
    "material": "Rubber"
  }
]

JS:

   $.ajax({
        url: "https://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20json%20where%20url%20%3D%22http%3A%2F%2Fgoo.gl%2FaZgYDB%22&format=json&diagnostics=true&callback=",
        success: function (data) {
            var item_html="";
            $(data.query.results.json).each(function(key, value) {
              $.each(value,function(key, value){                             
               item_html += '<h3>'+key+' - '+value+'</h3>';                        
              });
            });            
           $('#area').append(item_html);
        }
    });

您可以检查键值并添加如下内容

$.each(value, function (key, value) {   
      item_html += '<h3>' + key + ' - ' + value + '</h3>';
      if(key=='link')
         item_html += '<h3>something</h3>';
      if(key=='color')
         item_html += '<h3>something else</h3>';
  });
演示

我想你只是在寻找一个简单的if语句:

if(value == "google.com"){
    item_html += '<h3>Text</h3>';
}
if(value == "Black" && key == "color"){
    item_html += '<h3>SecondText</h3>';   
}

如果想要确定的话,还可以同时检查键和值(第二个if语句)。

工作小提琴