[英]Select option without value using jQuery
Line of code in question: 有问题的代码行:
$(this).find('select option:first').val();
If my select has this structure: 如果我的选择具有以下结构:
<select>
<option> -- choose -- </option>
<option value="some_value"> Some text</option>
</select>
the jQuery code I posted above will return --choose--
as a value. 我上面发布的jQuery代码将返回--choose--
作为值。 Is there a way I could understand if the option has a value or not, instead of returning the text in it? 有什么办法可以让我理解选项是否具有值,而不是返回其中的文本?
$(this).find('select option:first').attr('value');
注意:如果未设置value属性,则返回undefined
In your case, if your first option
have no value
attribute, you can use this: 对于您的情况,如果您的第一个option
没有value
属性,则可以使用以下方法:
$(this).find('select option[value]:first').val()
This returns the first option
tag from your select
but requiring that it haves the value
attribute. 这将从您的select
返回第一个option
标签,但要求它具有value
属性。
UPDATE: 更新:
Based on @Samuel Caillerie's comment, you can use multiple attribute selectors to avoid IE bizarre behaviours: 根据@Samuel Caillerie的评论,您可以使用多个属性选择器来避免IE怪异的行为:
select option[value][value!=""]:first
That worked on Chrome and IE 10 with compatibility mode set to IE 8. 在兼容模式设置为IE 8的Chrome和IE 10上有效。
您可以这样做:
$(this).find('select option:selected').attr('value');
尝试这个:
$(this).find('select option:first').attr('value');
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.