最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to prevent accordion from toggling when button in header is clicked? - Stack Overflow

programmeradmin3浏览0评论

I'm using bootstrap's accordion class and want to have buttons in the header that can be clicked without toggling the accordion. Here's example HTML:

<div class="body">
    <div class="panel panel-default" style="width: 80%">
        <div class="panel-heading" data-toggle="collapse" data-target="#container1" style="cursor: pointer;">
            <h4 class="panel-title" style="display: inline-block;">
               title
            </h4>
        <div style="float: right; width: 130px; text-align: right;"><span style="color: red;">test</span></div>
            <button type="button" class="btn btn-xs btn-primary" style="float: right;" onclick="foo(event);">Button</button>
    </div>
    <div id="container1" class="panel-collapse collapse">
        <div class="panel-body">
            panel content
        </div>
    </div>
    </div>
</div>

I tried using an onclick handler with e.preventDefault(); to stop the accordion from triggering, but it didn't work:

window.foo = function(e) {
    console.log("foo");
    $(".body").append("<br>foo");
    e.preventDefault();
}

JSFIDDLE

How can I prevent the accordion from triggering when the button is clicked?

I'm using bootstrap's accordion class and want to have buttons in the header that can be clicked without toggling the accordion. Here's example HTML:

<div class="body">
    <div class="panel panel-default" style="width: 80%">
        <div class="panel-heading" data-toggle="collapse" data-target="#container1" style="cursor: pointer;">
            <h4 class="panel-title" style="display: inline-block;">
               title
            </h4>
        <div style="float: right; width: 130px; text-align: right;"><span style="color: red;">test</span></div>
            <button type="button" class="btn btn-xs btn-primary" style="float: right;" onclick="foo(event);">Button</button>
    </div>
    <div id="container1" class="panel-collapse collapse">
        <div class="panel-body">
            panel content
        </div>
    </div>
    </div>
</div>

I tried using an onclick handler with e.preventDefault(); to stop the accordion from triggering, but it didn't work:

window.foo = function(e) {
    console.log("foo");
    $(".body").append("<br>foo");
    e.preventDefault();
}

JSFIDDLE

How can I prevent the accordion from triggering when the button is clicked?

Share Improve this question asked Jun 28, 2014 at 18:06 NateNate 28.4k38 gold badges136 silver badges228 bronze badges 1
  • check this out stackoverflow.com/questions/20545477/… – Don Srinath Commented Jun 28, 2014 at 18:18
Add a comment  | 

1 Answer 1

Reset to default 20

You want to stop event bubbling, so you use stopPropagation:

window.foo = function(e) {
    e.stopPropagation();
}

Demo: http://jsfiddle.net/Bye8K/3/

发布评论

评论列表(0)

  1. 暂无评论