Only Bob's second answer is correct:
$("#sel")[0].selectedIndex
Works:
http://jsfiddle.net/b9chris/wxeVN/1/
Using .attr()
works only if the user (or browser's DOM restore) has not changed the option selected since the page loaded:
http://jsfiddle.net/b9chris/wxeVN/
You could implement this as a jQuery extension, and get a little more info in the process:
(function($) {
$.fn.selectedOption = function() {
var sel = this[0];
return sel.options[sel.selectedIndex];
};
})(jQuery)
$('button').click(function() {
$('#output').text('selected index: ' + $('select').selectedOption().index);
});
http://jsfiddle.net/b9chris/wxeVN/102/
What's returned by .selectedOption()
is the actual option tag, so you can access .index
, .value
, and .text
- a bit more convenient than just the index in typical usage.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…