jQuery追加循环重复

时间:2019-03-21 18:50:10

标签: javascript jquery

我正在尝试添加循环中的一些信息,并在console.log上获得正确的结果,但是在添加之后,每个结果都会被添加几次

我的代码:

let success = function(res) {
        let coinsRedemption = res['coinsRedempt']
        let rewardsRedemption = res['rewardsRedempt']

for(i=0; i<coinsRedemption.length;i++){
    let coinType = coinsRedemption[i]['coin_type']
    let coinTime = coinsRedemption[i]['visit_date']
    let firstName = coinsRedemption[i]['first_name']

    for(j=0; j<rewardsRedemption.length; j++){
        let rewardName = rewardsRedemption[i]['reward_name']
        let rewardDateClaimed = rewardsRedemption[i]['date_claimed']
        let rewardCompleteDate = rewardsRedemption[i]['complete_date']
        let firstName1 = rewardsRedemption[i]['first_name']

        $('#redeemptionsTable tbody').append(`
        <tr class='redempTableRows'>
            <td class='coin-redemption'>${coinType}</td>
            <td class='coin-redemption-time'>${coinTime}</td>
            <td class='coin-redemption-location'> ${firstName}</td>
        </tr>
        <tr class='rewardRedempTableRows'>
            <td class='reward-redemption'>${rewardName}</td>
            <td class='reward-redemption-time'>${rewardDateClaimed}</td>
            <td class='reward-redemption-location'>${firstName1}</td>
        </tr> `)
    }

结果

enter image description here

如何避免将结果仅附加一次?

PS:我已经研究过回答相同问题的问题,但是它们并没有帮助我。

1 个答案:

答案 0 :(得分:0)

redempTableRows行应在外部循环而不是内部循环中输出。

let success = function(res) {
  let coinsRedemption = res['coinsRedempt']
  let rewardsRedemption = res['rewardsRedempt']

  for (i = 0; i < coinsRedemption.length; i++) {
    let coinType = coinsRedemption[i]['coin_type']
    let coinTime = coinsRedemption[i]['visit_date']
    let firstName = coinsRedemption[i]['first_name']
    $("#redemptionsTable tbody").append(`
      <tr class='redempTableRows'>
          <td class='coin-redemption'>${coinType}</td>
          <td class='coin-redemption-time'>${coinTime}</td>
          <td class='coin-redemption-location'> ${firstName}</td>
      </tr>`);
    for (j = 0; j < rewardsRedemption.length; j++) {
      let rewardName = rewardsRedemption[i]['reward_name']
      let rewardDateClaimed = rewardsRedemption[i]['date_claimed']
      let rewardCompleteDate = rewardsRedemption[i]['complete_date']
      let firstName1 = rewardsRedemption[i]['first_name']

      $('#redeemptionsTable tbody').append(`
        <tr class='rewardRedempTableRows'>
            <td class='reward-redemption'>${rewardName}</td>
            <td class='reward-redemption-time'>${rewardDateClaimed}</td>
            <td class='reward-redemption-location'>${firstName1}</td>
        </tr> `)
    }
  }
}