jQuery 从事件处理程序调用时,Bootstrap Dropdown 切换不起作用

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16702464/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 17:37:20  来源:igfitidea点击:

Bootstrap Dropdown toggle doesn't work when called from an event handler

jquerytwitter-bootstrapdrop-down-menu

提问by Arman Bimatov

I have an element, dropdown, and some jquery to toggle the dropdown dynamically. However, the toggle doesn't work when called from the event handler. I've already tried everything suggested by related Stackoverflow answers, but nothing works :(

我有一个元素、下拉列表和一些 jquery 来动态切换下拉列表。但是,从事件处理程序调用时切换不起作用。我已经尝试了相关 Stackoverflow 答案建议的所有内容,但没有任何效果:(

JavaScript:

JavaScript:

$(function(){
  //$(".dropdown-toggle").dropdown('toggle'); // this works
  $('#click').click(function(){
    $(".dropdown-toggle").dropdown('toggle'); // this doesn't
  });
});

HTML:

HTML:

<div class="dropdown clearfix">
   <a class="dropdown-toggle" data-toggle="dropdown" href="#">Dropdown trigger</a>
   <ul id="dropdown" class="dropdown-menu" role="menu" aria-labelledby="dropdownMenu">
      <li><a tabindex="-1" href="#">Action</a></li>
      <li><a tabindex="-1" href="#">Another action</a></li>
      <li><a tabindex="-1" href="#">Something else here</a></li>
      <li class="divider"></li>
      <li><a tabindex="-1" href="#">Separated link</a></li>
    </ul>
  </div>
<br>
<div id="click">Click to toggle</div>

And here is the working (not!) sample: http://bootply.com/61988

这是工作(不是!)示例:http: //bootply.com/61988

回答by PSL

Just stop the event from propagating and it should work.

只需停止传播事件,它就可以工作。

$(function(){
  //$(".dropdown-toggle").dropdown('toggle'); // this works
  $('#click').click(function(e){
      e.stopPropagation();
    $(".dropdown-toggle").dropdown('toggle');// this doesn't
  });
});

Fiddle

小提琴

Bootply

引导