简体   繁体   English

将具有相同类名的表单输入字段放入数组中

[英]Put form input fields with same class name into an array

So I have some fields like this: 所以我有一些像这样的领域:

[1] [2] [3] with attributes: name=item1,item2,item3 and class = item

What I want to do is get all three fields into an array: 我想要做的是将所有三个字段都放入一个数组中:

so: 所以:

array = [1,2,3];

Is there a way to do this using the unique class attribute: "item" ? 有没有一种方法可以使用独特的class属性:“ item”?

You can use Array.map() method to return an array out of attribute: 您可以使用Array.map()方法从属性返回数组:

 var items = $('.item').attr('name').split(','), // convert to array arr = [].map.call(items, function(value) { // use return +value.match(/\\d/)[0]; // return the number value from the array "items" }); $('pre').html(JSON.stringify(arr)); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <p name='item1,item2,item3' class='item'>item</p> <pre></pre> 

Get the items and loop through them. 获取项目并遍历它们。 Adding each one to your list. 将每个添加到您的列表。

var items = [];
$('.item').each(function(index, value){
  //where value is an input
  items.push(value);
});

试试这个$(".items").toArray()以获得相同的结果,可能是可行的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM