使用JS触发Bootstrap下拉列表 [英] Trigger Bootstrap Dropdown with JS
本文介绍了使用JS触发Bootstrap下拉列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我需要通过JavaScript打开一个Bootstrap下拉菜单。 这个答案建议添加和删除打开
类,但是当我尝试时,没有任何反应。添加不同的类工作正常。 Bootstrap阻止我这样做吗?
I need to open a Bootstrap dropdown menu via JavaScript. This answer suggests adding and removing the open
class, but when I try that, nothing happens. Adding a different class works fine. Is Bootstrap preventing me from doing this?
HTML
<input type="button" value="Add Classes" />
<div class="dropdown">
<a data-toggle="dropdown" href="#">Dropdown Trigger</a>
<div class="dropdown-menu">Dropdown Content</div>
</div>
JS
$('input').click(function () {
$('.dropdown').addClass('open');
$('.dropdown').addClass('test-class');
});
推荐答案
你的主要问题是你没有停止点击事件传播到文档
。 Bootstrap在文档
上设置一个关闭下拉列表的事件监听器。
Your main problem is that you aren't stopping the click event from propagating to the document
. Bootstrap sets an event listener on the document
that closes dropdowns.
$('input').on('click', function (e) {
e.stopPropagation();
$(this).next('.dropdown').find('[data-toggle=dropdown]').dropdown('toggle');
});
jsFiddle - http://jsfiddle.net/8p6Wd/2/
jsFiddle - http://jsfiddle.net/8p6Wd/2/
这篇关于使用JS触发Bootstrap下拉列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文