构建所有选择框的ID数组

我正在尝试使用精彩的jQuery插件将一堆选择框转换为可编辑: https : //github.com/indrimuska/jquery-editable-select 。

第一步是获取所有选择框的ID。 来自http://jsfiddle.net/49rk6ph7/69/我试过这个,但我没有得到:

[s1,s2] 

我怎样才能使这个工作?

 var test = []; test = $("select").each(function() { test.push($(this).attr('id')) }); console.log(test); 
  
115x175 mm 120x160 mm 120x287 mm
115x175 mm 120x160 mm 120x287 mm

您的代码的问题是因为您将test分配给each()的结果,这是一个jQuery对象,而不是您最初定义的数组。 只需从该语句中删除test =

请注意,您还可以通过使用map()而不是each()循环以及使用不显眼的JS事件处理程序删除过时on*属性来使逻辑更简洁。 像这样的东西:

 var test = $("select").map(function() { return this.id }).get(); console.log(test); $('#s1, #s2').change(function() { $(this).next().val($(this).val()); }); 
  

在jQuery调用之前删除test = 。 您正在覆盖原始testarrays。

这就是你所需要的:

 var test = []; $("select").each(function() { test.push($(this).attr("id")); }); console.log(test);