【问题标题】:store .each() , html() in single variable or in array for further use将 .each() , html() 存储在单个变量或数组中以供进一步使用
【发布时间】:2015-01-27 20:02:22
【问题描述】:

我有 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

【问题讨论】:

    标签: jquery html each


    【解决方案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() 已经返回一个。

    【讨论】:

      【解决方案2】:

      最好和最简单的方法是使用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
      });
      

      【讨论】:

      • @web.bluffer...很高兴为您提供帮助:)
      猜你喜欢
      • 1970-01-01
      • 2017-11-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-10-21
      相关资源
      最近更新 更多