【问题标题】:how to get the values of all elements with the same class如何获取具有相同类的所有元素的值
【发布时间】:2013-10-02 13:46:27
【问题描述】:

我有一堆输入文本字段在同一类emps_l 中具有不同的值。我想循环使用该类的所有元素并将值存储到数组中! 贝娄是我所做的:

var emps = new Array();     
$.each(($(".emps_l").val()),function()({        
      emps.push($(".emps_l").val());        
});
console.log(emps);

我完全迷失了,任何帮助将不胜感激!

【问题讨论】:

  • jQuery 中的大多数 getter 函数只作用于第一个匹配的元素(因此返回单个值)。执行 $(".emps_l").val() 返回 DOM 中第一个具有 emps_l 类的元素的值,而执行 $(".emps_l").val(1); 会将具有 emps_l 类的每个元素的值设置为 1,然后返回该 jQuery 对象。 /跨度>

标签: jquery arrays loops


【解决方案1】:

您可以使用.map()this.value 来创建数组

var emps = $(".emps_l").map(function () {
    return this.value
}).get()

【讨论】:

    【解决方案2】:
    var emps = []; // This is considered slightly faster than new array
    
    $('.emps_1').each(function(){
        emps.push(this.value);
    });
    
    console.log(emps);
    

    【讨论】:

    • 只能使用this.value 而不是$(this).val()。节省您(不必要地)调用 jQuery 函数,并且更容易/更快地键入。
    【解决方案3】:

    使用这个:

    var emps = new Array();     
    $.each(($(".emps_l:input").val()),function(index , item )({        
          emps.push($(item ).val());        
    });
    console.log(emps);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-08-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-02-17
      • 1970-01-01
      相关资源
      最近更新 更多