【问题标题】:Dynamically generated content using only last array item仅使用最后一个数组项动态生成的内容
【发布时间】:2019-12-13 15:21:47
【问题描述】:

我有以下数据数组:

let testimonials = [
        {"name":"Carol Jadraque","service":"Logo Design","quote":"Anton from EG-graphics displays a high degree of professionalism; he is always responsive, caters to the client’s wants & needs and is highly reliable."},
        {"name":"Tony Salloum","service":"Animation","quote":"With a professional approach, attention to details and high dedication to his work, Anton has produced several videos for us, all done on schedule and to the highest of standards. I will definitely use his services again."},
        {"name":"Irina Feldman","service":"Website Design","quote":"Anton is reliable and attentive to detail. We loved his creative approach and ability to quickly respond to our requests and concerns."},
        {"name":"Lilianne Lord","service":"Private Tutoring","quote":"Anton is super friendly, skilled and genuinely interested in helping you out! Highly professional tutor and would recommend him to anyone looking for inspiration as well as a tutor!"},
    ];

我有一个循环应该使用该数据生成内容,如下所示:

for (var i = 0; i < testimonials.length; i++) { 
   var content = "";
   content += '<div class="item"> <div class="testi_item"> <p class="testimonial-text">' + testimonials[i].quote + '</p> <h4 class="testimonial-name">' + testimonials[i].name + '</h4><h5 class="testimonial-service">' + testimonials[i].service + '</h5> </div> </div>';
   console.log(content);
}
$('.testi_slider').html(content);

问题在于它使用数组中第 4 个对象的数据生成 4 个内容实例。我相信我的错误可能与使用 testimonials[i] 有关,但是我不确定正确的方法是什么,因为 i 的值应该从 0 开始到 3。

谁能解释我的错误在哪里?

【问题讨论】:

  • 您在每次迭代时初始化内容。将var content = ""; 移动到循环之前的位置。
  • content = "" 在循环中。为什么你认为它应该有效?

标签: javascript arrays object for-loop


【解决方案1】:

问题是您在循环的每次迭代中都重新清空了content 字符串。考虑改为在循环之前声明content

var content = "";
for (var i = 0; i < testimonials.length; i++) { 

   content += '<div class="item"> <div class="testi_item"> <p class="testimonial-text">' + testimonials[i].quote + '</p> <h4 class="testimonial-name">' + testimonials[i].name + '</h4><h5 class="testimonial-service">' + testimonials[i].service + '</h5> </div> </div>';
   console.log(content);
}
$('.testi_slider').html(content);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-08-14
    • 2014-06-25
    • 2011-04-21
    • 2014-02-21
    • 2014-10-22
    • 2023-03-11
    • 2017-07-25
    • 2021-11-15
    相关资源
    最近更新 更多