javascript - 如何循环遍历类并在数组中添加文本

标签 javascript jquery arrays class

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

我得到了一个包含所有类文本的数组,已经按照我想要的方式格式化了。问题是我需要用数组中的文本更改每个类的 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 数组中的文本。我尝试以很多不同的方式循环它,但我错过了一些东西

最佳答案

仅循环元素,否则您将覆盖:

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

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

});

关于javascript - 如何循环遍历类并在数组中添加文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22763231/

相关文章:

java - 不知道为什么我有这个错误 Exception in thread "main"java.lang.ArrayIndexOutOfBoundsException : 0

c - 指向数组中第一个元素的指针! (C)

javascript - 从 AngularJS 中的多个复选框获取值

javascript - 在表单将 Mootools 1.1 发送到 Mootools 1.4.1 后更新 div

javascript - 如何使 slider 响应(codepen)?

javascript - 检查浏览器是否已完成页面加载

javascript - 确定浏览器是否支持 iFrame 中的 javascript?

javascript - jquery 移动滑动

php - AJAX请求不显示信息

c - 为矩阵动态分配数组