Skip to content

Instantly share code, notes, and snippets.

@g8up
Created August 31, 2015 11:59
Show Gist options
  • Save g8up/26493ff65f657802566b to your computer and use it in GitHub Desktop.
Save g8up/26493ff65f657802566b to your computer and use it in GitHub Desktop.
捕获 <select />指定 <option /> 的点击事件
(function ($) {
function CustomSelectHandler( selectElem, optionSelector, clickHandler){
selectElem.data('click.status', 0 );
selectElem.on('click.option', function(e){
var status = selectElem.data('click.status');
if(status == 0){
selectElem.data('click.status', 1 );// unfold
}else if( status == 1){
if( selectElem.find('option:selected').is(optionSelector) ){
clickHandler && clickHandler(e);
}
selectElem.data('click.status', 0 );
}
}).blur(function(e){
selectElem.data('click.status', 0 );
});
}
/**
* 捕获 <select />指定 <option /> 的点击事件(哪怕不触发 change 事件,也能捕获)
* @param {String} optionSelector 指定 option 的 CSS Selector
* @param {Function} selectHandler 响应函数,默认向其回传 event 对象
*/
$.fn.selectOption = function (optionSelector, selectHandler) {
this.each(function () {
var $this = $(this);
CustomSelectHandler($this, optionSelector, selectHandler);
});
}
})(jQuery);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment