单击里面,避免关闭下拉菜单

时间:2014-08-01 21:59:08

标签: javascript jquery html twitter-bootstrap-3 drop-down-menu

我有一个Twitter Bootstrap下拉菜单。正如所有Twitter Bootstrap用户都知道的那样,下拉菜单会在点击时关闭(甚至点击其中)。

为避免这种情况,我可以在下拉菜单上轻松附加点击事件处理程序,只需添加着名的event.stopPropagation()即可。

<ul class="nav navbar-nav">
  <li class="dropdown mega-dropdown">
    <a href="javascript:;" class="dropdown-toggle" data-toggle="dropdown">
      <i class="fa fa-list-alt"></i> Menu item 1
      <span class="fa fa-chevron-down pull-right"></span>
    </a>
    <ul class="dropdown-menu mega-dropdown-menu">
      <li>
        <div id="carousel" class="carousel slide" data-ride="carousel">
          <ol class="carousel-indicators">
            <li data-slide-to="0" data-target="#carousel"></li>
            <li class="active" data-slide-to="1" data-target="#carousel"></li>
          </ol>
          <div class="carousel-inner">
            <div class="item">
              <img alt="" class="img-rounded" src="img1.jpg">
            </div>
            <div class="item active">
              <img alt="" class="img-rounded" src="img2.jpg">
            </div>
          </div>
          <a data-slide="prev" role="button" href="#carousel" 
             class="left carousel-control">
            <span class="glyphicon glyphicon-chevron-left"></span>
          </a>
          <a data-slide="next" role="button" href="#carousel" 
             class="right carousel-control">
            <span class="glyphicon glyphicon-chevron-right"></span>
          </a>
        </div>
      </li>
    </ul>
  </li>
</ul>

这看起来很简单且非常常见,因为carousel-controls(以及carousel indicators)事件处理程序被委托给document对象,click这些元素的事件(上一个/下一个控件,......)将被“忽略”。

$('ul.dropdown-menu.mega-dropdown-menu').on('click', function(event){
    // The event won't be propagated up to the document NODE and 
    // therefore delegated events won't be fired
    event.stopPropagation();
});

依赖于Twitter Bootstrap下拉列表hide / hidden事件不是解决方案,原因如下:

  • 两个事件处理程序提供的事件对象都不提供对单击元素的引用
  • 我无法控制下拉菜单内容,因此无法添加flag类或属性

This fiddle是正常行为,this fiddle添加了event.stopPropagation()

更新

感谢Roman his answer。我还找到了answer that you can find below

38 个答案:

答案 0 :(得分:336)

删除数据属性data-toggle="dropdown"并实现下拉列表的打开/关闭可能是一种解决方案。

首先处理点击链接以打开/关闭下拉列表,如下所示:

$('li.dropdown.mega-dropdown a').on('click', function (event) {
    $(this).parent().toggleClass('open');
});

然后听取下拉列表外的点击以关闭它:

$('body').on('click', function (e) {
    if (!$('li.dropdown.mega-dropdown').is(e.target) 
        && $('li.dropdown.mega-dropdown').has(e.target).length === 0 
        && $('.open').has(e.target).length === 0
    ) {
        $('li.dropdown.mega-dropdown').removeClass('open');
    }
});

以下是演示: http://jsfiddle.net/RomaLefrancois/hh81rhcm/2/

答案 1 :(得分:272)

这也应该有帮助

$(document).on('click', 'someyourContainer .dropdown-menu', function (e) {
  e.stopPropagation();
});

答案 2 :(得分:36)

Bootstrap provides the following function:

                 | This event is fired immediately when the hide instance method 
hide.bs.dropdown | has been called. The toggling anchor element is available as the 
                 | relatedTarget property of the event.

因此,实现此功能应该能够禁止关闭下拉列表。

$('#myDropdown').on('hide.bs.dropdown', function (e) {
    var target = $(e.target);
    if(target.hasClass("keepopen") || target.parents(".keepopen").length){
        return false; // returning false should stop the dropdown from hiding.
    }else{
        return true;
    }
});

答案 3 :(得分:27)

我也找到了解决方案。

假设Twitter Bootstrap Components相关事件处理程序被委托给document对象,我循环附加的处理程序并检查当前单击的元素(或其父项之一)是否受委托事件的影响

$('ul.dropdown-menu.mega-dropdown-menu').on('click', function(event){
    var events = $._data(document, 'events') || {};
    events = events.click || [];
    for(var i = 0; i < events.length; i++) {
        if(events[i].selector) {

            //Check if the clicked element matches the event selector
            if($(event.target).is(events[i].selector)) {
                events[i].handler.call(event.target, event);
            }

            // Check if any of the clicked element parents matches the 
            // delegated event selector (Emulating propagation)
            $(event.target).parents(events[i].selector).each(function(){
                events[i].handler.call(this, event);
            });
        }
    }
    event.stopPropagation(); //Always stop propagation
});

希望它能帮助任何寻找类似解决方案的人。

谢谢大家的帮助。

答案 4 :(得分:26)

绝对最佳答案是在课程下拉菜单

之后放置一个表单标签

所以你的代码是

<ul class="dropdown-menu">
  <form>
    <li>
      <div class="menu-item">bla bla bla</div>
    </li>
  </form>
</ul>

答案 5 :(得分:20)

$('body').on("click", ".dropdown-menu", function (e) {
    $(this).parent().is(".open") && e.stopPropagation();
});

这可能适用于任何条件。

答案 6 :(得分:18)

这可能会有所帮助:

$("dropdownmenuname").click(function(e){
   e.stopPropagation();
})

答案 7 :(得分:10)

<强> jQuery的:

<script>
  $(document).on('click.bs.dropdown.data-api', '.dropdown.keep-inside-clicks-open', function (e) {
    e.stopPropagation();
  });
</script>

<强> HTML:

<div class="dropdown keep-inside-clicks-open">
  <button class="btn btn-primary dropdown-toggle" type="button" data-toggle="dropdown">
     Dropdown Example
    <span class="caret"></span>
  </button>
  <ul class="dropdown-menu">
    <li><a href="#">HTML</a></li>
    <li><a href="#">CSS</a></li>
    <li><a href="#">JavaScript</a></li>
  </ul>
</div>

<强>演示

通用: https://jsfiddle.net/kerryjohnson/omefq68b/1/

使用此解决方案的演示:http://jsfiddle.net/kerryjohnson/80oLdtbf/101/

答案 8 :(得分:8)

我只是添加如下 onclick 事件来不关闭下拉菜单。

 <div class="dropdown-menu dropdown-menu-right" onclick="event.stopPropagation()" aria-labelledby="triggerId">

答案 9 :(得分:5)

您也可以使用 form 标签。示例:

<div class="dropdown-menu">
    <form>
        Anything inside this wont close the dropdown!
        <button class="btn btn-primary" type="button" value="Click me!"/>
    </form>
    <div class="dropdown-divider"></div>
    <a class="dropdown-item" href="#">Clik this and the dropdown will be closed</a>
    <a class="dropdown-item" href="#">This too</a>
</div>

来源:https://getbootstrap.com/docs/5.0/components/dropdowns/#forms

答案 10 :(得分:4)

我尝试了这个简单的事情,它就像一种魅力。

我将下拉菜单元素从<div>更改为<form>,并且效果很好。

<div class="nav-item dropdown" >
  <a href="javascript:;" class="nav-link dropdown-toggle" data-toggle="dropdown">
   Click to open dropdown
 </a>
 <form class="dropdown-menu   ">
  <ul class="list-group text-black">
     <li class="list-group-item"  >
     </li>
     <li class="list-group-item"   >
     </li>
  </ul>
</form>

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js"></script>

<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js"></script>


<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" rel="stylesheet"/>


<div class="nav-item dropdown" >
  <a href="javascript:;" class="nav-link dropdown-toggle" data-toggle="dropdown">
   Click to open dropdown
 </a>
 <form class="dropdown-menu   ">
  <ul class="list-group text-black">
     <li class="list-group-item"  >
      List Item 1
     </li>
     <li class="list-group-item"   >
         LI 2<input class="form-control" />
     </li>
     <li class="list-group-item"   >
        List Item 3
     </li>
  </ul>
</form>

答案 11 :(得分:4)

$('body').on("click", ".dropdown-menu", function (e) {
    $(this).parent().is(".show") && e.stopPropagation();
});

这在2018年有效

答案 12 :(得分:4)

  
$('ul.nav.navbar-nav').on('click.bs.dropdown', function(e){
    var $a  = $(e.target), is_a = $a.is('.is_a');
    if($a.hasClass('dropdown-toggle')){   
        $('ul.dropdown-menu', this).toggle(!is_a);
        $a.toggleClass('is_a', !is_a);
    }
}).on('mouseleave', function(){
    $('ul.dropdown-menu',this).hide();
    $('.is_a', this).removeClass('is_a');
});

我再次将其更新为尽可能最智能和最实用的功能。当你在导航栏外面悬停时它现在关闭,当你在里面时保持打开状态。简单完美。

答案 13 :(得分:4)

我最近遇到了类似的问题,尝试了不同的解决方法,删除了数据属性data-toggle="dropdown",并通过click调用来监听event.stopPropagation()

第二种方式看起来更可取。 Bootstrap开发人员也使用这种方式。 在源文件中,我发现了下拉元素的初始化:

// APPLY TO STANDARD DROPDOWN ELEMENTS
$(document)
.on('click.bs.dropdown.data-api', clearMenus)
.on('click.bs.dropdown.data-api', '.dropdown form', function (e) { e.stopPropagation() })
.on('click.bs.dropdown.data-api', toggle, Dropdown.prototype.toggle)
.on('keydown.bs.dropdown.data-api', toggle, Dropdown.prototype.keydown)
.on('keydown.bs.dropdown.data-api', '.dropdown-menu', Dropdown.prototype.keydown)
}(jQuery);

所以,这一行:

.on('click.bs.dropdown.data-api', '.dropdown form', function (e) { e.stopPropagation() })

建议您可以在容器form内添加.dropdown元素,以避免关闭下拉菜单。

答案 14 :(得分:3)

您可以停止点击传播下拉列表,然后使用carousel javascript methods手动重新实现轮播控件。

$('ul.dropdown-menu.mega-dropdown-menu').on('click', function(event) {
    event.stopPropagation();
});

$('a.left').click(function () {
    $('#carousel').carousel('prev');
});

$('a.right').click(function () {
    $('#carousel').carousel('next');
});

$('ol.carousel-indicators li').click(function (event) {
    var index = $(this).data("slide-to");
    $('#carousel').carousel(index);
});

这是jsfiddle

答案 15 :(得分:3)

例如Bootstrap 4 Alpha就有这个菜单事件。为什么不用?

// PREVENT INSIDE MEGA DROPDOWN
$('.dropdown-menu').on("click.bs.dropdown", function (e) {
    e.stopPropagation();
    e.preventDefault();                
});

答案 16 :(得分:3)

Bootstrap自身通过支持下拉列表中的<form>标签本身解决了此问题。他们的解决方案非常容易掌握,您可以在这里阅读:https://github.com/twbs/bootstrap/blob/v4-dev/js/src/dropdown.js

归结为防止在文档元素处传播,并且仅在与选择器'click.bs.dropdown.data-api'匹配的'.dropdown .your-custom-class-for-keep-open-on-click-elements'类型的事件中这样做。

或在代码中

$(document).on('click.bs.dropdown.data-api', '.dropdown .keep-open-on-click', (event) => {
    event.stopPropagation();
});

答案 17 :(得分:3)

使用Angular2 Bootstrap,您可以在大多数情况下使用nonInput:

<div dropdown autoClose="nonInput">
  

nonInput - (默认)在单击任何元素时自动关闭下拉列表 - 只要单击的元素不是输入或textarea。

https://valor-software.com/ng2-bootstrap/#/dropdowns

答案 18 :(得分:2)

而不是编写一些javascript或jquery代码(重新发明轮子)。上述方案可以通过bootstrap自动关闭选项进行管理。 您可以为自动关闭

提供任一值
  1. always - (默认)会在点击任何元素时自动关闭下拉列表。

  2. outsideClick - 仅在用户点击下拉列表外的任何元素时自动关闭下拉列表。

  3. 已停用 - 禁用自动关闭

  4. 看看下面的plunkr:

    http://plnkr.co/edit/gnU8M2fqlE0GscUQtCWa?p=preview

    $conn->errorInfo

    希望这会有所帮助:)

答案 19 :(得分:2)

我知道这个问题是专门针对jQuery的,但是对于使用AngularJS的任何有此问题的人,您可以创建一个处理此问题的指令:

angular.module('app').directive('dropdownPreventClose', function() {
    return {
        restrict: 'A',
        link: function(scope, element, attrs) {
          element.on('click', function(e) {
            e.stopPropagation(); //prevent the default behavior of closing the dropdown-menu
          });
        }
    };
});

然后只需将属性dropdown-prevent-close添加到触发菜单关闭的元素中,它就应该阻止它。对我来说,这是一个自动关闭菜单的select元素:

<div class="dropdown-menu">
  <select dropdown-prevent-close name="myInput" id="myInput" ng-model="myModel">
    <option value="">Select Me</option>
  </select>
</div>

答案 20 :(得分:2)

[Bootstrap 4 Alpha 6] [Rails] 对于rails开发人员,e.stopPropagation()会导致link_to data-method的不良行为不等于get,因为它会默认将您的所有请求都返回为get

为了解决这个问题,我建议使用这个通用的解决方案

$('.dropdown .dropdown-menu').on('click.bs.dropdown', function() {
  return $('.dropdown').one('hide.bs.dropdown', function() {
    return false;
  });
});

&#13;
&#13;
$('.dropdown .dropdown-menu').on('click.bs.dropdown', function() {
  return $('.dropdown').one('hide.bs.dropdown', function() {
    return false;
  });
});
&#13;
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/css/bootstrap.min.css" integrity="sha384-rwoIResjU2yc3z8GV/NPeZWAv56rSmLldC3R/AZzGRnGxQQKnKkoFVhFQhNUwEyJ" crossorigin="anonymous">
<script src="https://code.jquery.com/jquery-3.1.1.slim.min.js" integrity="sha384-A7FZj7v+d/sdmMqp/nOQwliLvUsJfDHW+k9Omg/a/EheAdgtzNs3hpfag6Ed950n" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/tether/1.4.0/js/tether.min.js" integrity="sha384-DztdAPBWPRXSA/3eYEEUWrWCy7G5KFbe8fFjk5JAIxUYHKkDx6Qin1DkWx51bBrb" crossorigin="anonymous"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/js/bootstrap.min.js" integrity="sha384-vBWWzlZJ8ea9aCX4pEW3rVHjgjt7zpkNpZk+02D9phzyeVkE+jo0ieGizqPLForn" crossorigin="anonymous"></script>

<ul class="nav navbar-nav">
  <li class="dropdown mega-dropdown">
    <a href="javascript:;" class="dropdown-toggle" data-toggle="dropdown">
      <i class="fa fa-list-alt"></i> Menu item 1
      <span class="fa fa-chevron-down pull-right"></span>
    </a>
    <ul class="dropdown-menu mega-dropdown-menu">
      <li>
        <div id="carousel" class="carousel slide" data-ride="carousel">
          <ol class="carousel-indicators">
            <li data-slide-to="0" data-target="#carousel"></li>
            <li class="active" data-slide-to="1" data-target="#carousel"></li>
          </ol>
          <div class="carousel-inner">
            <div class="item">
              <img alt="" class="img-rounded" src="img1.jpg">
            </div>
            <div class="item active">
              <img alt="" class="img-rounded" src="img2.jpg">
            </div>
          </div>
          <a data-slide="prev" role="button" href="#carousel" class="left carousel-control">
            <span class="glyphicon glyphicon-chevron-left"></span>
          </a>
          <a data-slide="next" role="button" href="#carousel" class="right carousel-control">
            <span class="glyphicon glyphicon-chevron-right"></span>
          </a>
        </div>
      </li>
    </ul>
  </li>
</ul>
&#13;
&#13;
&#13;

答案 21 :(得分:2)

我修改了@Vartan的答案,使其可以与Bootstrap 4.3一起使用。他的解决方案不适用于最新版本,因为target属性始终会返回下拉菜单的根div,无论单击何处。

代码如下:

$('.dropdown-keep-open').on('hide.bs.dropdown', function (e) {
  if (!e.clickEvent) {
    // There is no `clickEvent` property in the `e` object when the `button` (or any other trigger) is clicked. 
    // What we usually want to happen in such situations is to hide the dropdown so we let it hide. 
    return true;
  }

  var target = $(e.clickEvent.target);

  return !(target.hasClass('dropdown-keep-open') || target.parents('.dropdown-keep-open').length);
});
<div class="dropdown dropdown-keep-open">
  <button class="btn btn-secondary dropdown-toggle" type="button" id="dropdownMenuButton" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
    Dropdown button
  </button>
  <div class="dropdown-menu" aria-labelledby="dropdownMenuButton">
    <a class="dropdown-item" href="#">Action</a>
    <a class="dropdown-item" href="#">Another action</a>
    <a class="dropdown-item" href="#">Something else here</a>
  </div>
</div>

答案 22 :(得分:1)

.dropdown内容中,将.keep-open类放在任何标签上,如下所示:

$('.dropdown').on('click', function (e) {
    var target = $(e.target);
    var dropdown = target.closest('.dropdown');
    if (target.hasClass('keep-open')) {
        $(dropdown).addClass('keep-open');
    } else {
        $(dropdown).removeClass('keep-open');
    }
});

$(document).on('hide.bs.dropdown', function (e) {
    var target = $(e.target);
    if ($(target).is('.keep-open')) {
        return false
    }
});

以前的案例避免了与容器对象相关的事件,现在容器继承了keep-open类并在关闭之前进行检查。

答案 23 :(得分:1)

对我来说最简单的解决方案是:

  • keep-open类添加到不应导致下拉关闭的元素
  • 这段代码完成剩下的工作:
$('.dropdown').on('click', function(e) {
    var target = $(e.target);
    var dropdown = target.closest('.dropdown');
    return !dropdown.hasClass('open') || !target.hasClass('keep-open');
});

答案 24 :(得分:1)

这对我有帮助

$('.dropdown-menu').on('click', function (e) {
     if ($(this).parent().is(".open")) {
         var target = $(e.target);
         if (target.hasClass("keepopen") || target.parents(".keepopen").length){
                    return false; 
                }else{
                    return true;
                }
            }            
});

您的下拉菜单元素必须是这样的(请注意类dropdown-menukeepopen

<ul role="menu" class="dropdown-menu topmenu-menu eserv_top_notifications keepopen">

上面的代码可防止对整个<body>进行出价,而不是对类为dropdown-menu的特定元素进行出价。

希望这对某人有帮助。

谢谢。

答案 25 :(得分:1)

我发现没有任何解决方案可以使用默认的bootstrap导航。 这是我解决这个问题的方法:

       $(document).on('hide.bs.dropdown', function (e) {
        if ($(e.currentTarget.activeElement).hasClass('dropdown-toggle')) {
          $(e.relatedTarget).parent().removeClass('open');
          return true;
        }
        return false;
       });

答案 26 :(得分:1)

我知道已有一个先前的答案建议使用表单,但提供的标记不正确/理想。这是最简单的解决方案,根本不需要javascript,也不会破坏你的下拉列表。适用于Bootstrap 4。

<form class="dropdown-item"> <!-- Your elements go here --> </form>

答案 27 :(得分:0)

我是这样做的:

$(element).on({
    'mouseenter': function(event) {
        $(event.currentTarget).data('mouseover', true);
    },
    'mouseleave': function(event) {
        $(event.currentTarget).data('mouseover', false);
    },
    'hide.bs.dropdown': function (event) {
        return !$(event.currentTarget).data('mouseover');
    }
});

答案 28 :(得分:0)

$(function() {
    $('.mega-dropdown').on('hide.bs.dropdown', function(e) {
        var $target = $(e.target);
        return !($target.hasClass("keep-open") || $target.parents(".keep-open").size() > 0);
    });

    $('.mega-dropdown > ul.dropdown-menu').on('mouseenter', function() {
        $(this).parent('li').addClass('keep-open')
    }).on('mouseleave', function() {
        $(this).parent('li').removeClass('keep-open')
    });
});

答案 29 :(得分:0)

如果使用return false或stopPropagation()方法,可能会遇到一些问题,因为事件将被中断。 试试下面的代码,就可以了:

$(function() {
    $('.dropdown').on("click", function (e) {
            $('.keep-open').removeClass("show");
    });
    $('.dropdown-toggle').on("click", function () {
            $('.keep-open').addClass("show");
    });

    $( ".closeDropdown" ).click(function() {
        $('.dropdown').closeDropdown();
    });
});
jQuery.fn.extend({
    closeDropdown: function() {
        this.addClass('show')
            .removeClass("keep-open")
            .click()
            .addClass("keep-open");
    }
  });

在HTML中:

<div class="dropdown keep-open" id="search-menu" >
    <button  class="btn dropdown-toggle btn  btn-primary" type="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
    <i class="fa fa-filter fa-fw"></i> 
    </button>
    <div class="dropdown-menu">
        <button class="dropdown-item" id="opt1" type="button">Option 1</button>
        <button class="dropdown-item" id="opt2" type="button">Option 2</button>
        <button type="button" class="btn btn-primary closeDropdown">Close</button>
    </div>
</div>

如果要关闭沉船,则:

`$('#search-menu').closeDropdown();`

答案 30 :(得分:0)

您需要在“下拉菜单”类别中添加“点击保持”

答案 31 :(得分:0)

在Bootstrap 4中,您也可以执行以下操作:

$.ajax({
    headers: {'X-CSRFToken': '{{ csrf_token }}' },
    type: 'POST',
    data: data,
    processData: false,
    contentType: false
});

其中$('#dd-link').on('hide.bs.dropdown', onListHide) function onListHide(e) { if(e.clickEvent && $.contains(e.relatedTarget.parentNode, e.clickEvent.target)) { e.preventDefault() } } 是具有#dd-link属性的锚元素或按钮。

答案 32 :(得分:0)

您可以通过下面的代码来解决此问题。

$(document).on('click.bs.dropdown.data-api', '.keep_it_open', function (e) {
  e.stopPropagation();
});
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/css/bootstrap.min.css" rel="stylesheet"/>
<meta name="viewport" content="width=device-width, initial-scale=1">
    <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js"></script>
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/css/bootstrap.min.css">
  <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/js/bootstrap.min.js"></script>


<div class="dropdown keep_it_open">
        <button class="btn btn-primary dropdown-toggle" type="button" data-toggle="dropdown">Dropdown Example
        <span class="caret"></span></button>
        <ul class="dropdown-menu">
          <li><a href="#">HTML</a></li>
          <li><a href="#">CSS</a></li>
          <li><a href="#">JavaScript</a></li>
        </ul>
      </div>

答案 33 :(得分:0)

您只需在链接本身的点击事件上执行event.stopPropagation。 像这样的东西。

    $(".dropdown-menu a").click((event) => {
         event.stopPropagation()
         let url = event.target.href
         //Do something with the url or any other logic you wish
    })

编辑:如果有人看到此答案并正在使用react,它将无法正常工作。 React处理JavaScript事件的方式有所不同,到您的react事件处理程序被调用时,该事件已被触发并传播。为了克服这个问题,您应该像这样手动附加事件

handleMenuClick(event) {
   event.stopPropagation()
   let menu_item = event.target
   //implement your logic here.
}
componentDidMount() {
    document.getElementsByClassName("dropdown-menu")[0].addEventListener(
        "click", this.handleMenuClick.bind(this), false)
   }
}

答案 34 :(得分:0)

引导程序4

$('.dropdown-menu[data-handledropdownclose="true"]').on("click.bs.dropdown", function (e) {
    if ($(this).parent().hasClass("show")) {
        var target = $(e.target);

        if (!(target.hasClass("CloseDropDown") || target.parents(".CloseDropDown").length)) {
            e.stopPropagation();
        }
    }
});

<div class="dropdown">
    <button type="button" class="btn-no-border dropdown-toggle" data-toggle="dropdown">
        <img src="~/Content/CSS/CssImages/Icons/usr_icon.png" alt="" title="language" class="float-right" />
    </button>

    <div class="dropdown-menu profile-menu-logout" data-handledropdownclose="true">
        <div class="prof-name">
            <i class="fa fa-user"></i> Hello World
        </div>

        <hr />

        <div>
            <a href="/Test/TestAction" class="CloseDropDown">
                <i class="fa fa-briefcase"></i>
                <span>Test Action</span>
            </a>
        </div>

        <div>
            <nav>
                <ul class="nav-menu-prof padding-0">
                    <li class="menu-has-children">
                        <a href="#">
                            <span class="cyan-text-color">
                                Test 2
                            </span>
                        </a>

                        <ul id="ulList" class="padding-0 pad-left-25">
                            <li>
                                <a href="/Test/Test2" class="action currentmenu"> Test 1 </a>
                                <a href="/Test/Test2" class="action CloseDropDown"> Test 2 </a>
                            </li>
                        </ul>
                    </li>
                </ul>
            </nav>
        </div>

        <div>
            <a href="/Account/Logout" class="cyan-text-color CloseDropDown">
                <i class="fa fa-power-off"></i>
                <span>Logout</span>
            </a>
        </div>
    </div>
</div>

答案 35 :(得分:0)

$(document).click(function (event) {
    $target = $(event.target);
    if ($target.closest('#DivdropFilterListItemsCustomer').length == 1) {
        $('#DivdropFilterListItemsCustomer').addClass('dropdown-menu show');        
    } else {
        $('#DivdropFilterListItemsCustomer').removeClass('dropdown-menu 
           show').addClass('dropdown-menu');
    }
});
DivdropFilterListItemsCustomer is id of drop down 
 [Show id and drop down ][1]

#A2ZCode

答案 36 :(得分:0)

仅当在引导程序下拉列表外触发点击事件时关闭下拉列表,这对我有用:

JS档案:

    $('.createNewElement').on('click.bs.dropdown.data-api', '.tags-btn-group.keep-open-dropdown', function (e) {
        var target = $(e.target);
        if (target.hasClass("dropdown-menu") || target.parents(".dropdown-menu").length) {
            e.stopPropagation();
        }
    });

HTML文件:

<!-- button: -->
<div class="createNewElement">
                <div class="btn-group tags-btn-group keep-open-dropdown">

                    <div class="dropdown-toggle" data-toggle="dropdown" aria-expanded="false">OPEN DROPDOWN</div>

                    <ul class="dropdown-menu">
                        WHAT EVER YOU WANT HERE...
                    </ul>

                </div>
</div>

答案 37 :(得分:-1)

$(function() {
var closeble = false;
$('body').on('click', function (e) {
    if (!$(event.target).is("a.dropdown-toggle")) {
        closeble = false;
    }

});
$('.dropdown').on({
    "click": function(event) {
        if ($(event.target).closest('.dropdown-toggle').length) {
            closeble = true;
        } else {
            closeble = false;
        }
    },
    "hide.bs.dropdown": function() {
        return closeble;
    }
});

});