首页 > 解决方案 > 递归创建不同的id,用于jquery转换成html表

问题描述

我正在尝试使用 jquery 将 api 的数据正确地注入到 html 表中。我缺少的是递归地创建一个 id 到“tr”的语法,如下所示:

<tr id=...></tr> 

为了注入一行数据。

这是当前代码:

$( document ).ready(function() {
$.getJSON('https://official-joke-api.appspot.com/random_ten', function(i) { 
console.log(i);
let titre = i[0];
console.log(titre);

  $.each(titre, function (index, element) {
    let head = (`<th scope="col">${index}</th>`);
    $('#head').append(head);
  });

  $.each(i, function (index, element){
    let rangee = `<tr id="i"></tr>`;
    $('#table-body').append(rangee);
    $.each(element, function (key, value){
      let row = (`<tr>
        <td scope="col">${value}</td>
        </tr>`)

    $('#i').append(row);

    });
  });
  });
 });

问题在于:

let rangee = `<tr id="i"></tr>`;

我不知道如何将“i”检测为迭代次数......
现在,我所有的数据都在我的表格的第一排。
我尝试了各种带有引号变体的奇怪语法,但现在没有任何效果......

谢谢您的帮助 !

标签: htmljquerycssjsonajax

解决方案


您可以寻求帮助index而不是i

$( document ).ready(function() {
$.getJSON('https://official-joke-api.appspot.com/random_ten', function(i) { 
console.log(i);
let titre = i[0];
console.log(titre);

  $.each(titre, function (index, element) {
    let head = (`<th scope="col">${index}</th>`);
    $('#head').append(head);
  });

  $.each(i, function (index, element){
    let rangee = `<tr id="${index}"></tr>`;
    $('#table-body').append(rangee);
    $.each(element, function (key, value){
      let row = (`<tr>
        <td scope="col">${value}</td>
        </tr>`)

    $(`#${index}`).append(row);

    });
  });
  });
 });

推荐阅读