我正在使用div和span标签创建一个选择框,以便可以为iPhone和iPad使用样式化的框。它的效果很好,但是一旦用户单击该框并显示了下拉选择,则删除该选择列表的唯一方法就是选择一个选择,或者再次单击选择框。我正在寻找一个功能,该功能将关闭用户的选择列表,单击该页面上除列表(当列表打开时)以外的其他任何内容。这是我处理选项列表显示的功能

jQuery的:

    $(this).children('.selectedOption,.selectDropDownArrow').click(function(){
        if($(this).parent().children('.selectOptions').css('display') == 'none'){
            $(this).parent().children('.selectOptions').css('display','block');
        } else {
            $(this).parent().children('.selectOptions').css('display','none');
        }
    });


现在,我需要类似这样的东西来处理对网站其他部分的点击:

$('!.selectedOption,!.selectDropDownArrow').click(function() {
  if (!$('.selectOptions').css('display','none')) {
    $('.selectOptions').css('display','none');
  }
});


有人知道实现此目标的方法吗?

最佳答案

由于您要切换可见性,因此请尝试更改代码css以直接使用toggle


  描述:显示或隐藏匹配的元素。


码:

$(this).children('.selectedOption,.selectDropDownArrow').click(function(){
   $(this).parent().children('.selectOptions').toggle();
});


然后使用:not选择所有内容,但不选择类和hide


  说明:选择与给定不匹配的所有元素
  选择器。


码:

$(":not(.selectedOption,.selectDropDownArrow)").click(function(){
  $('.selectOptions').hide();
});


更新

当您单击和元素时,事件就会冒泡给它的祖先,在这种情况下,元素将被常规的隐藏处理程序隐藏。

为避免这种情况,请使用stopPropagation

参考:


  描述:防止事件使DOM树冒泡,
  防止任何父处理程序收到该事件的通知。


码:

$(":not(.selectedOption, .selectDropDownArrow)").click(function (e) {
    alert('general');
    e.stopPropagation();
});

$(".selectedOption,.selectDropDownArrow").click(function (e) {
    alert('specific');
    e.stopPropagation();
});


演示:http://jsfiddle.net/IrvinDominin/eb9wj/

10-05 20:39
查看更多