在JS中从迭代的JSON数组元素对象创建HTML表行

时间:2017-07-13 18:23:59

标签: javascript json

我使用wiki API搜索某些东西,然后我得到了JSON,它在query.search中有我想要的数据。

0 {ns: 0, title: "Help", size: 3677, wordcount: 433, snippet: "<span class=\"searchmatch\">Help</span> is any form …mmand-line shells that invokes documentations and", …}

1 {ns: 0, title: "Online help", size: 7326, wordcount: 380, snippet: "(HTML), which includes HTML <span class=\"searchmat…earchmatch\">help</span> is also provided via live", …}

2 {ns: 0, title: "Help desk", size: 9491, wordcount: 1296, snippet: "A <span class=\"searchmatch\">help</span> desk is a …ated to a company's or institution's products and", …}

...

我需要title的值,因此for循环使用

进行迭代
for (var i = 0; i < data.query.search.length; i++) {
var result = data.query.search[i];
var title = result.title; 
console.log(title); }

现在我想创建一个表并将每个标题值放入单独的行中,我使用此代码但它不起作用

  var table = document.getElementById("resultTable");

  var row = table.insertRow(i);
  var cell1 = row.insertCell(i);

  cell1.innerHTML = data.query.search[i].title;

在HTML部分我有

<div>
<table id="resultTable"></table>
</div>

我是否必须将表创建代码放入单独的for循环或使用[i]是错误的?

以下是整个代码:

function build_wiki_search_url(pattern) {
var base_url = "https://en.wikipedia.org/w/api.php";
var format = "&format=json";
var request_url = "?  action=query&format=json&prop=info&inprop=url&list=search&srsearch=";
var url = base_url + request_url + pattern;
return url;
}
$(document).ready(function() {
$("#gosearch").click(function(e) {
    e.preventDefault();
    console.log("Submit button clicked");
    var pattern = $("#search").val();
    var url = build_wiki_search_url(pattern);
    $.ajax( {
        type: "GET",
        url: url,
        dataType: 'jsonp',
        success: function(data) {
            console.log(data.query.search); 

 for (var i = 0; i < data.query.search.length; i++) {
 var result = data.query.search[i];
 var title = result.title;
  console.log(title);

 function drawTableHor(data) {
var table1 = document.getElementById("resultTable1");
for (var i = 0; i < data.query.search.length; i++) {
  var row = table1.insertRow();
  for(var prop in data.query.search[i]) {
    if(prop !== 'title') continue;
      var cell = row.insertCell();
      cell.innerHTML = data.query.search[i][prop];
  }
}
};
   drawTableHor(data);

   }

1 个答案:

答案 0 :(得分:0)

var row = table.insertRow(i);
var cell1 = row.insertCell(i);

在这里你使用相同的i(在我认为的循环内)。虽然行是可以的,因为在迭代的每个步骤中你处理一个新行,我想它对单元格不起作用,因为从第二步开始,你尝试在一个奇怪的索引处插入一个单元格:2,等等,分别在第1,第1和第2位等处没有任何东西。

有了你的代码,我得到了一张只有第一个标题的表格。我想说,你根本不需要函数中的那些索引,并假设你想要将每个标题值放在不同的行中。检查下面的代码。还要注意,有一种替代方案可以放置数据&#34;垂直&#34; =标题值在一行中):

&#13;
&#13;
var data = {
query: {
search: [
{ns: 0, title: "Help", size: 3677, wordcount: 433, snippet: "<span class=\"searchmatch\">Help</span> is any form …mmand-line shells that invokes documentations and"},
{ns: 0, title: "Online help", size: 7326, wordcount: 380, snippet: "(HTML), which includes HTML <span class=\"searchmat…earchmatch\">help</span> is also provided via live"},
{ns: 0, title: "Online Super help", size: 7326, wordcount: 380, snippet: "(HTML), which includes HTML <span class=\"searchmat…earchmatch\">help</span> is also provided via live"},
{ns: 0, title: "Help desk", size: 9491, wordcount: 1296, snippet: "A <span class=\"searchmatch\">help</span> desk is a …ated to a company's or institution's products and"}
]
}
};
function drawTableHor(data) {
    var table1 = document.getElementById("resultTable1");
    for (var i = 0; i < data.query.search.length; i++) {
      var row = table1.insertRow();
      for(var prop in data.query.search[i]) {
        if(prop !== 'title') continue;
          var cell = row.insertCell();
          cell.innerHTML = data.query.search[i][prop];
      }
    }
}
// alternative
function drawTableVert(data) {
    var table2 = document.getElementById("resultTable2");
    var rows = [], props = [];
    for(var prop in data.query.search[0]) {
        rows.push(table2.insertRow());
        props.push(prop);
    }
    rows.forEach(function(row, index) {
      for (var i = 0; i < data.query.search.length; i++) {
        if(props[index] !== 'title') continue;  
          var cell = row.insertCell();
          cell.innerHTML = data.query.search[i][props[index]];
      }
    });
}
// call each function passing your data
drawTableHor(data);
drawTableVert(data);
&#13;
table {
  border-collapse: collapse;
  border-spacing: 0.5em;
}
td, th {
  border: 1px solid #999;
  padding: 0.5rem;
  text-align: left;
}
&#13;
<div>
<h1>Data is inserted "horizontally"</h1>
<table id="resultTable1"></table>
<br>
<h1>Data is inserted "vertically"</h1>
<table id="resultTable2"></table>
</div>
&#13;
&#13;
&#13;

希望有所帮助:)

<强>更新

&#13;
&#13;
   
function build_wiki_search_url(pattern) {
var base_url = "https://en.wikipedia.org/w/api.php";
var request_url = "?action=query&format=json&prop=info&inprop=url&list=search&srsearch=";
var url = base_url + request_url + pattern;
return url;
}
function drawTableHor(data) {
var table1 = document.getElementById("resultTable1");
for (var i = 0; i < data.query.search.length; i++) {
  var row = table1.insertRow();
  for(var prop in data.query.search[i]) {
    if(prop !== 'title') continue;
      var cell = row.insertCell();
      cell.innerHTML = data.query.search[i][prop];
  }
}
}
// UNCOMMENT everything commented out here to follow your original setup.
$(document).ready(function() {
/*$("#gosearch").click(function(e) {
    e.preventDefault();*/
    var pattern = 'iteration'; //$("#search").val();
    var url = build_wiki_search_url(pattern);
    $.ajax({
        type: "GET",
        url: url,
        dataType: 'jsonp',
        success: function(data) { 
            drawTableHor(data);
            }
   });
 //});
});
&#13;
table {
  border-collapse: collapse;
  border-spacing: 0.5em;
}
td, th {
  border: 1px solid #999;
  padding: 0.5rem;
  text-align: left;
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
<h1>Data is inserted "horizontally"</h1>
<table id="resultTable1"></table>
</div>
&#13;
&#13;
&#13;

我正在寻找迭代&#39;这个词就是例如。在您的情况下,您应该在代码中注意我注意到的一些事情。我的意思是点击#search element上的函数。