简体   繁体   English

将Click事件添加到Bootstrap下拉切换时的奇怪行为

[英]Weird behavior when adding click event to Bootstrap dropdown-toggle

I have a Bootstrap dropdown button with the following markup: 我有一个带有以下标记的Bootstrap下拉按钮:

<div class="btn-group dropup">
    <a class="btn dropdown-toggle" data-toggle="dropdown" href="#">Test<span class="caret"></span></a>
    <ul class="dropdown-menu">
        <li>
            <a href="#">Link 1</a>
            <a href="#">Link 2</a>
            <a href="#">Link 3</a>
        </li>
    </ul>
</div>

When you click on a.dropdown-toggle , Bootstrap's javascript toggles the ul.dropdown-menu 's visibility by adding the class open to the div.btn-group . 当您单击a.dropdown-toggle ,Bootstrap的javascript通过将类open添加到div.btn-group来切换ul.dropdown-menu的可见性。 All this is well and good. 这一切都很好。

The problem I'm experiencing occurs when I add my own javascript function to the a.dropdown-toggle 's click event. 我将自己的JavaScript函数添加到a.dropdown-toggle的click事件中时,遇到了我遇到的问题。 Something like this: 像这样:

$('a.dropdown-toggle').click(function (e) {
    e.preventDefault();
    $('a.dropdown-toggle').html('Testing...');
});

When I do this something weird happens. 当我这样做时,会发生一些奇怪的事情。 When you click the button, it expands the menu as desired EXCEPT when you click directly on the .caret in the button. 当您单击按钮时,除了直接单击按钮中的.caret ,它还会根据需要扩展菜单。 When you click directly on the .caret , it only executes my click event. 当您直接单击.caret ,它仅执行我的click事件。

How can I resolve this and have clicks directly on the .caret toggle the menu like clicking anywhere else on the button does. 我该如何解决此问题,并直接单击.caret切换菜单,就像单击按钮上的其他任何位置一样。

http://jsfiddle.net/UZkQL/ http://jsfiddle.net/UZkQL/

In your fiddle you have: 在您的小提琴中,您有:

$('a.dropdown-toggle').html('Testing...<span class="caret"></span>');

The issue is that you recreate the span element with the carat, which seems to make it not have a click handler bound to it. 问题是您用克拉重新创建了span元素,这似乎使其没有绑定到单击处理程序。 A quick and dirty fix would be: 一个快速而肮脏的修复方法是:

$('a.dropdown-toggle').click(function (e) {
    e.preventDefault();
    if ($('a.dropdown-toggle').text().indexOf('ing...') == -1) {
        $('a.dropdown-toggle').find('span').before('ing...');
    }
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM