【问题标题】:Close dropdown when click something else单击其他内容时关闭下拉菜单
【发布时间】:2012-12-19 01:07:51
【问题描述】:

如何关闭“selectOptions”?现在我只能在单击“span.selected”或“span.selectArrow”时关闭它。单击另一个列表或仅在列表之外时,我也想将其关闭。

function enableSelectBoxes(){
$('div.selectBox').each(function(){
    $(this).children('span.selected').html($(this).children('div.selectOptions').children('span.selectOption:first').html());
    $(this).attr('value',$(this).children('div.selectOptions').children('span.selectOption:first').attr('value'));

    $(this).children('span.selected,span.selectArrow').click(function(){
        if($(this).parent().children('div.selectOptions').css('display') == 'none'){
            $(this).parent().children('div.selectOptions').css('display','block');
        }
        else
        {
            $(this).parent().children('div.selectOptions').css('display','none');
        }
    });
    $(this).find('span.selectOption').click(function(){
        $(this).parent().css('display','none');
        $(this).closest('div.selectBox').attr('value',$(this).attr('value'));
        $(this).parent().siblings('span.selected').html($(this).html());
    });
}); 
}

【问题讨论】:

    标签: jquery-selectbox


    【解决方案1】:

    你可以这样做:

    $(document).click(function(event) {
        //If the user clicks somewhere on the page, but not on the autocomplete.
        if(event.target != $("#autocomplete")[0]) {
            $("#autocomplete").hide();
        }
    });
    

    【讨论】:

    • 是的,谢谢它部分工作,因为我有多个这些选择框,它只适用于第一个。
    • 您必须修改此代码以使其在您的代码中工作。您可以使用包含当前打开的自动完成类的变量并使用它而不是在代码中硬编码 ID。
    • 为什么是[0]?并且选择器不适用于多个选择器,例如: if(event.target !=$('.selected, .selectArrow')[0]){}
    猜你喜欢
    • 1970-01-01
    • 2022-07-08
    • 1970-01-01
    • 2018-02-06
    • 1970-01-01
    • 1970-01-01
    • 2021-11-17
    • 1970-01-01
    相关资源
    最近更新 更多