从具有相同类的字段中获取值,添加到数组中

Get value from fields with same class, add to array

本文关键字:获取 添加 数组 字段 同类      更新时间:2023-09-26

所以我有一个动态的文本框列表,所有的文本框都有相同的类,像这样:

<input type="text" id="value1" class="list-value" />
<input type="text" id="value2" class="list-value" />
<input type="text" id="value3" class="list-value" />
<input type="text" id="value4" class="list-value" />

当点击链接时,我需要将所有文本框中的值加载到数组中:

$('a#link').click(function() {
    //add to array here
});

我该怎么做呢?

你可以这样做:

var values = $('.list-value').map(function() { return this.value; }).get();

"。map()"方法将像"。each()"一样遍历元素列表,但它接受返回值并累积一个数组。最后的"。get()"是获得"原始"数组而不是jQuery对象(数组的包装器)所必需的,但这并不总是必要的;