【问题标题】:How to loop through classes and add text in array如何遍历类并在数组中添加文本
【发布时间】:2014-03-31 13:45:38
【问题描述】:

在给定最大字母数的情况下,我正在尝试创建一个省略文本的函数。

我得到了一个包含所有类文本的数组,已经按照我想要的方式进行了格式化。问题是我需要用数组中的文本更改每个类的 text()。

这是我的代码:

var array = $('.elipse').map(function(){
    return $(this).text();
}).get();


var i;
var teste = [];

for (i=0;i<array.length;i++){
    if (array[i].length > 30){

    teste.push(array[i].substr(0,10));

    } else {
        teste.push(array[i]);
    }
}

for (var i=0;i<teste.length;i++){

     $('.elipse').each(function(){

      $(this).text(teste[i]);

    });

  } 

问题出在最后一个 for 循环中。包含 elipse 类的每个元素的每个文本都必须更改为 teste 数组中的文本。我试图用很多不同的方式循环它,但我错过了一些东西

【问题讨论】:

  • 每个椭圆文本将始终是 teste 数组中的最后一项,因为每次 for 循环进入时,它都会从 start 再次开始交互每个函数

标签: javascript jquery arrays class


【解决方案1】:

只循环元素,否则你会覆盖:

$('.elipse').each(function(i){

  $(this).text(teste[i]);

});

【讨论】:

  • 谢谢,不知道如何正确使用每个功能..只是缺少参数:))
猜你喜欢
  • 2013-04-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-07-12
  • 2012-04-10
  • 1970-01-01
相关资源
最近更新 更多