建立所有选择框的ID数组 [英] Build an array of ids of all select boxes
问题描述
我正在尝试使用出色的jQuery插件将一堆选择框转换为可编辑状态: https://github.com/indrimuska/jquery-editable-select .
I'm trying to convert a bunch of select boxes to be editable using the fantastic jQuery plugin: https://github.com/indrimuska/jquery-editable-select.
第一步是获取所有选择框的ID.来自 http://jsfiddle.net/49rk6ph7/69/我已经尝试过了,但是我没有得到:
The first step is to get the ids of all select boxes. From http://jsfiddle.net/49rk6ph7/69/ I have tried this but I'm not getting:
[s1,s2]
我该如何工作?
var test = [];
test = $("select").each(function() {
test.push($(this).attr('id'))
});
console.log(test);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="select-editable">
<select id="s1" onchange="this.nextElementSibling.value=this.value">
<option value=""></option>
<option value="115x175 mm">115x175 mm</option>
<option value="120x160 mm">120x160 mm</option>
<option value="120x287 mm">120x287 mm</option>
</select>
<input type="text" name="format" value="" />
</div>
<div class="select-editable">
<select id="s2" onchange="this.nextElementSibling.value=this.value">
<option value=""></option>
<option value="115x175 mm">115x175 mm</option>
<option value="120x160 mm">120x160 mm</option>
<option value="120x287 mm">120x287 mm</option>
</select>
<input type="text" name="format" value="" />
</div>
推荐答案
代码的问题是因为您正在将test
分配给each()
的结果,该结果是一个jQuery对象,而不是您原来的数组定义.只需从该语句中删除test =
.
The issue with your code is because you're assigning test
to the result of each()
, which is a jQuery object, not the array you originally define. Simply remove test =
from that statement.
请注意,您还可以通过使用map()
而不是each()
循环,并通过使用不引人注意的JS事件处理程序删除过时的on*
属性,来使逻辑更加简洁.像这样:
Note that you can also make the logic more succinct by using map()
instead of an each()
loop and by removing the outdated on*
attributes with unobtrusive JS event handlers. Something like this:
var test = $("select").map(function() {
return this.id
}).get();
console.log(test);
$('#s1, #s2').change(function() {
$(this).next().val($(this).val());
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="select-editable">
<select id="s1">
<option value=""></option>
<option value="115x175 mm">115x175 mm</option>
<option value="120x160 mm">120x160 mm</option>
<option value="120x287 mm">120x287 mm</option>
</select>
<input type="text" name="format" value="" />
</div>
<div class="select-editable">
<select id="s2">
<option value=""></option>
<option value="115x175 mm">115x175 mm</option>
<option value="120x160 mm">120x160 mm</option>
<option value="120x287 mm">120x287 mm</option>
</select>
<input type="text" name="format" value="" />
</div>
这篇关于建立所有选择框的ID数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!