也许这可能是一个愚蠢的问题,但我不是jQuery的专家,所以我需要一些解释。我想在我的选择中获取所选选项的值。所以我写了这段代码:
var actual_option = $(this).find('option:selected', this).map(function ()
{
return this.value;
}).get();
当用户点击我的选择时,这个变量将通过选项值进行定值,问题是最终的结果是:
[ “2”]
而不是
2
如何避免括号?
答案 0 :(得分:5)
此处无需.map()
或.get()
。您返回的值包含括号,因为.get()
返回一个数组。
考虑$(this)
代表<select>
- 代码,您只需执行以下操作:
var actual_option = $(this).val();
答案 1 :(得分:2)
在数组中返回值的原因是因为您正在使用map()
- 在这种情况下您实际上并不需要这样做。
假设this
引用了select元素本身$(this).val()
将起作用:
var actual_option = $(this).val();
答案 2 :(得分:1)
var actual_option = $(this).find('option:selected', this).map(function ()
{
return this.value;
}).get(0);
试试这个
答案 3 :(得分:1)
.get()
将整个集合转换为本机数组。您可以使用.get(0)
:
var actual_option = $(this).find('option:selected').map(function ()
{
return this.value;
}).get(0);
// ^
但这很过分,只需调用.val()
即可返回所选元素集合中第一个元素的值。
var actual_option = $(this).val();
还值得指出.find()
只需要一个参数,因此.find('option:selected', this)
应该只是.find('option:selected')
您似乎尝试使用$('option:selected', this)
的选择器速记,该速记等同于$(this).find('option:selected')
。