Jquery 1.4 - select - onchange fired WITHOUT click- Firefox

后端 未结 1 1864
爱一瞬间的悲伤
爱一瞬间的悲伤 2021-01-14 23:39

I\'m seeing really strange behavior - in Firefox, if you have a select dropdown without any item selected, the onchange event fires onblur - even if you\'re just changing fo

1条回答
  •  离开以前
    2021-01-15 00:31

    Here's the answer I came up with, feel free to comment/improve:

    $("#mySelect").attr('selectedIndex', '-1');
    
    //Capture the initial selection of each dropdown
    $('select').each(function() {
        $(this).data('initialSelection', String($(this).attr('selectedIndex')));
    });
    
    //Add click event to all options. When clicked, change initial selection and unbind the click event
    $('select option').click(function() {
        $(this).parent().data('initialSelection', '').attr('selectedIndex', this.index).find('option').unbind('click');
    });
    
    //Onchange, check if initial selection is still -1. (If there is a click it will be reset to '') 
    //Otherwise, it was just a hover - reset selected index to -1
    $('select').change(function(e){
        if($(this).data('initialSelection') == '-1'){
             $(this).attr('selectedIndex', '-1');
        }
    });
    

    0 讨论(0)
提交回复
热议问题