jQuery从数组中多个元素的类属性获取值而无循环 [英] jQuery Get value from class attribute of multiple elements in array without loop

查看:118
本文介绍了jQuery从数组中多个元素的类属性获取值而无循环的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个类.select

<select class='select' name='select1' id='select1'>
  <option value='1'>1</option>
  <option value='2'>2</option>
  <option value='3'>3</option>
</select>

<select class='select' name='select2' id='select2'>
  <option value='4'>4</option>
  <option value='5'>5</option>
  <option value='6'>6</option>
</select>

<select class='select' name='select3' id='select3'>
  <option value='7'>7</option>
  <option value='8'>8</option>
  <option value='9'>9</option>
</select>

我知道可以借助这样的循环来实现

I know it can be achieved with the help of loop like this

var arr = [];
$('.select').each(function () {
   arr.push($(this).val());
});

但是我的代码中已经有很多循环了,我想知道如果没有循环,有什么方法可以实现

But I already have so many loops in the code and I'm wondering if is there any way it can be achievable without a loop

小提琴: http://jsfiddle.net/89cJC/

推荐答案

不,没有其他方法可以从多个元素中获取值,您必须遍历元素以从每个元素中获取值.

No, there's no other way to get the value from multiple elements, you have to iterate over the elements to get the value from each of them.

还有其他方法可以编写基本相同的代码

There are other ways to write basically the same code

var arr = $.map($('.select'), function (el) { return el.value; });

或者没有jQuery

or without jQuery

var elems = document.querySelectorAll('.select'),
    arr   = [];

for (var i=elems.length; i--;) arr.push(elems[i].value);

但是它们都在迭代,没有别的办法做到这一点.

but they all iterate, there's no other way to do that.

这篇关于jQuery从数组中多个元素的类属性获取值而无循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆