简体   繁体   中英

Weird behavior when adding click event to Bootstrap dropdown-toggle

I have a Bootstrap dropdown button with the following markup:

<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 . 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. 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. When you click directly on the .caret , it only executes my click event.

How can I resolve this and have clicks directly on the .caret toggle the menu like clicking anywhere else on the button does.

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. 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...');
    }
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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