How to check which <option> is actually clicked?
$('select').bind('click contextmenu',function(ev){
})
ev.target
is always a select
,not option
.
How can I know which one is now being clicked?
I can't do this:
$('option').bind('click contextmenu',function(ev){
})
Because it's not supported in IE8,and you can test it yourself!
It should also support right click, which fires the context开发者_开发技巧menu
event.
You can use the change event for the select box and can find the currently selected item using the following.
$("#sel").change ( function() {
alert ( $(this).find("option:selected").val() );
});
<option>
cannot catch events in IE. It has no independent life of its own; select boxes are single indivisible OS widgets in IE so a click on an option will always instead generate a click event for the <select>
element.
Whilst you might theoretically guess which option was being clicked from the event.clientY
property, that would require you to know exactly how IE had rendered the menu, including what fonts were in use (somewhat within your control), and whether the pop-up menu had popped up downwards or upwards or hit the edge of the screen so misaligned against the select element (not within your control at all). For a very short menu you could hope that it'll always open downwards and calculate from there, but it's not really reliable. It's almost always best to let the click go through and just see which option is selected afterwards.
As for oncontextmenu
, forget it. Right-clicking an <option>
in IE does nothing, no event is generated for you to catch at all. If you want right-clickable menus you will have to replace your <select>
with a JavaScript div-based pop-up analogue.
I suppose a solution might be to check the new value
of the select
: it should be the one coming from the option
your user just clicked on.
Or you might also check the selectedIndex
property of your select
: it should also point to the option
that's just been choosen.
Just use the val()-method on the select element:
$('select').bind('click contextmenu',function(ev){
var value = $(this).val();
})
OR:
$('select').change(function(ev){
var value = $(this).val();
})
This is from the jquery documentation as an example
$("select").change(function () {
var str = "";
$("select option:selected").each(function () {
str += $(this).text() + " ";
});
$("div").text(str);
})
.trigger('change');
From Selectors/selected
You could use the selected attribute. Something like this:
$("#YourSelect option:selected");
精彩评论