简体   繁体   English

.val()替代方案,它获取匹配元素集中所有元素的当前值

[英].val() alternative that gets the current value of all elements in the set of matched elements

I have 3 select elements and I'm using $(".select-elem select").val() to get the value of each select element in an array but it returns the value of only the first element in the set of matched elements. 我有3个选择元素,并且我使用$(".select-elem select").val()来获取数组中每个选择元素的值,但它仅返回匹配集合中第一个元素的值元素。 For example, if a user selects '2' for the first select element, '3' for the second, and '4' for the third, the val() function returns 2 instead of [2,3,4] . 例如,如果用户选择第一个选择元素“ 2”,第二个选择元素“ 3”,第三个选择“ 4”,则val()函数返回2而不是[2,3,4] Is there a function that would return an array containing values of all three select elements? 是否有一个函数将返回包含所有三个选择元素的值的数组?

<td class="select-elem">
<select>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
<option value="5">5</option>
<option value="6">6</option>
<option value="7">7</option>
<option value="8">8</option>
<option value="9">9</option>
</select>
</td>
<td class="select-elem">
<select>
<option value="0">0</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
<option value="5">5</option>
<option value="6">6</option>
<option value="7">7</option>
<option value="8">8</option>
<option value="9">9</option>
</select>
</td>
<td class="select-elem">
<select>
<option value="0">0</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
<option value="5">5</option>
<option value="6">6</option>
<option value="7">7</option>
<option value="8">8</option>
<option value="9">9</option>
</select>
</td>

Use map methods for this: 为此使用地图方法:

var values = $(".select-elem select").map(function() {
    return $(this).val();
}).get();

Create your own jquery method and use it wherever you need, find the following code 创建自己的jquery方法并在需要的地方使用它,找到以下代码

//create jquery method arrVal which returns array of values
$.fn.arrVal = function () {
  var valArr = [];
  $(this).each(function(){
    valArr.push($(this).val())
  })
  return valArr;
}

//call arrVal method
$('select').arrVal()

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

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