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. 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:
$(this).find('select option[value]:first').val()
This returns the first option
tag from your select
but requiring that it haves the value
attribute.
UPDATE:
Based on @Samuel Caillerie's comment, you can use multiple attribute selectors to avoid IE bizarre behaviours:
select option[value][value!=""]:first
That worked on Chrome and IE 10 with compatibility mode set to IE 8.
您可以这样做:
$(this).find('select option:selected').attr('value');
尝试这个:
$(this).find('select option:first').attr('value');
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.