2

次のマークアップがあります。

<select style="display:none">
    <option value='1'>1</option>
    <option vlaue='2'>2</option>
</select>
<input type="text" id="comboBox" />
<ul id="comboBoxData" style="display:none">
    <li id='1'>1</li>
    <li id='2'>2</li>
</ul>

および次の JQuery コード:

$(document).ready(function() {
    $('select').each(function() {
        var parent = this;
        $('#comboBoxData').on('click', 'li', function() {
            var value = $(this).prop('id');
            $(parent).val(value);
            $('#comboBox').val(value);
        });
    });   
    $('#comboBox').bind('focusin', function () {
        $('#comboBoxData').show();
    });   
    $('#comboBox').bind('focusout', function () {
        $('#comboBoxData').hide();
    });
});

LI の 1 つをクリックすると、クリック トリガーが発生する前に「comboBoxData」要素が消えます。これを回避する方法、またはフォーカスアウトと同じ効果を持つ代わりに使用できる代替イベントはありますか?

4

4 に答える 4

3

mouseenter および mouseleave イベントを配置し、isOver などのグローバル変数の値を変更します。

$('select').each(function() {
    var parent = this;
    $('#comboBoxData').on('click', 'li', function() {
        var value = $(this).prop('id');
        $(parent).val(value);
        $('#comboBox').val(value);
        $('#comboBoxData').hide();
    });
}); 
$('#comboBoxData').mouseover(function(){
    isOver = true;
}).mouseleave(function(){
    isOver = false;
});
$('#comboBox').bind('focusin', function () {
    $('#comboBoxData').show();
});   
$('#comboBox').bind('focusout', function () {
    if(!isOver){
        $('#comboBoxData').hide();
    }
});
于 2012-05-21T13:35:54.083 に答える
1

You do not require this:

 $('#comboBox').bind('focusout', function () {
        $('#comboBoxData').hide();
 });

instead use this inside $('#comboBoxData').on('click', 'li', function() {

if you are fine with plugin , you could just use this way:

$('#menu').bind('clickoutside', function (event) {
    $(this).hide();
});

You can get that plugin here

Also, I have changed the code without using the plugin: Please check the updated answer:

DEMO

于 2012-05-21T12:56:44.093 に答える
0

blur()関数で試す

$('#comboBox').blur(function () {
        $('#comboBoxData').hide();
    });

要素がフォーカスを失うと、blur イベントが要素に送信されます。

http://api.jquery.com/blur/から

于 2012-05-21T13:16:57.110 に答える
0

正確にはエレガントではありませんが、機能します。

$("body").click(function(event){   
    if(!$(event.target).is("#comboBoxData") && !$(event.target).is("#comboBox") ){    
        $("#comboBoxData").hide(); }
}); 


$(document).ready(function() {
    $('select').each(function() {
        $('#comboBoxData').on('click', 'li', function() {
        var value = $(this).prop('id');
                $('#comboBox').val(value);
           $('#comboBoxData').hide();
        });
    });   

    $('#comboBox').bind('focusin', function () {
    $('#comboBoxData').show();
  });
});
于 2012-05-21T13:51:10.557 に答える