$(this).find('select option:selected').each(function (i, val) {
var selectedValue = $(val).val(); //this returns the text from the option instead of the value
});
这是ie7中已知的问题吗?我没有找到任何相关信息。有什么可能的解决方法吗?谢谢。
$(this).find('select option:selected').each(function (i, val) {
var selectedValue = $(val).val(); //this returns the text from the option instead of the value
});
$(this).find('select').each(function (i, val) {
var selectedValue = $(this).val();
});
val()
方法有一个额外的好处,即在选择多个选项时能够返回一个值数组(我强调了这一点):
val()
方法主要用于获取表单元素(如input、select和textarea)的值。对于包含<select multiple="multiple">
元素的情况,val()
方法返回一个包含每个选定选项的数组;如果没有选定选项,则返回null。
尝试
用于单选
var selectedValue = $(this).val();
你只需要写上面这行代码就可以获取所选的值,不需要其他任何东西。
对于多选框,应该是:
var result = "";
$('#idselect option:selected').each(function(i, item)
{
result += $(this).val() + ", ";
});
$(val)
和$(this)
是等价的吗? - Johanthis
(在最外层)显然不是一个select
元素(它是包含一个或多个select
元素的东西),所以这样做行不通。 - T.J. Crowder这是一个预期的行为,因为您要求选项的值而不是元素本身。
不要过于复杂化事情。
$(this).find('select').each(function() {
var val = $(this).val();
});
$(this)
会返回一个jQuery DOM元素,但是this
返回什么? - Johanthis
返回未经jQuery包装的HTML元素,通常使用document.getElementById('id')
来接收。 - Starxthis
等于 $(this).get(0)
还是 $(this)[0]
? - Johaneach
,this
将会指向实际的 select
DOM 元素。$(this)
调用 jQuery 函数将其包装成 jQuery 对象,这样你就可以使用所有 jQuery 的好处了。 :-) - T.J. Crowder
select
元素上调用.val()
。 - Felix Kling.each()
中通常不需要接受任何参数 - 元素也可以通过this
访问。 - ThiefMaster