将.each(),html()存储在单个变量或数组中以供进一步使用

时间:2014-11-29 09:43:18

标签: jquery html each

我有tr,我从tr的每个td得到每个html(),现在我想将这些值/文本存储到变量中以供进一步使用,数组也可以使用,但是如何?

我目前的职能是

$(document).on('click', '.glyphicon-edit', function() {
    var vals = $(this).parent().parent().children();
    $(vals).each(function() {
        console.log($(this).html());
    });
});

这是我的控制台输出
汽车休息
51个
851个
5
48个
4
848个
54个
45792个
 

2 个答案:

答案 0 :(得分:1)

最简单的方法是使用array,如下所示: -

var arr=[];
$(document).on('click', '.glyphicon-edit', function(){ 
    var vals = $(this).parent().parent().children(); 
    $(vals).each(function(){ 
       arr.push($(this).html());  //push elements value in array 
    });
    console.log(arr);  //print array in console
});

答案 1 :(得分:1)

基于来自其他集合(数组或jQuery对象)的元素创建数组有一个特殊功能 - $.map

$(document).on('click', '.glyphicon-edit', function(){ 
  var vals = $(this).parent().parent().children();
  var htmls = $.map(vals, function() {
    return this.innerHTML;
  });
  console.log(htmls);
  // ... and then do whatever you want with those `htmls`
});

顺便说一句,没有必要再次将vals包装在jQuery对象中 - children()已经返回一个。

相关问题