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

javascript - Bootstrap collapse without unique identifier - Stack Overflow

programmeradmin0浏览0评论

I'm trying to use the bootstrap collapse plugin in such a way that a unique identifier is not required. Normally there is usually a single or a couple of collapsible elements on a page.

But my elements are generated dynamically and passing index keys is overkill.

What happens now is that if I toggle the collapse for element2, it will collapse element1. Obviously because they have the same ID.

Any way to achieve this without actually giving each collapsible element a unique id?

Here's a functional js fiddle:

/

I'm trying to use the bootstrap collapse plugin in such a way that a unique identifier is not required. Normally there is usually a single or a couple of collapsible elements on a page.

But my elements are generated dynamically and passing index keys is overkill.

What happens now is that if I toggle the collapse for element2, it will collapse element1. Obviously because they have the same ID.

Any way to achieve this without actually giving each collapsible element a unique id?

Here's a functional js fiddle:

http://jsfiddle.net/hhvrjnr3/

Share Improve this question asked Feb 6, 2015 at 16:04 NickNick 2,9806 gold badges37 silver badges72 bronze badges 7
  • 1 "passing index keys is overkill." This doesn't make much sense. Just generate both the link and the div with the same dynamically generated id. – vcanales Commented Feb 6, 2015 at 16:07
  • @devJunk is correct. How is it overkill? That and I don't see any other way – Kerry Hatcher Commented Feb 6, 2015 at 16:09
  • Well I wanted to try to get it to work without having to do that. Obviously That is a possibility and I had it working that way but the way the code is written now it will turn into a bit off a mess. EDIT: Using the ID is, in my opinion, an easy way out. Apparently it can't be done using the plugin itself. But it can be done by using jquery's find() and parent() methods. So i'll just do that then. – Nick Commented Feb 6, 2015 at 16:09
  • 2 Here you go - jsfiddle.net/hhvrjnr3/1 No need for id's :-) – Artur Filipiak Commented Feb 6, 2015 at 16:11
  • No need for the passive aggressiveness. I was just referring to the fact that passing the ids is in no way overkill. – vcanales Commented Feb 6, 2015 at 16:16
 |  Show 2 more comments

1 Answer 1

Reset to default 18

It can be done. First remove the data-target="#collapseExample" from the elements you want to collapse. Then add an extra class to your toggle button, I've added 'collapser'. That's not really needed, but it's nice to identify the toggle button. Then add some jQuery to do the toggling, in this case I am using next() to get the subsequent element to the toggle button which is your element you wish to collapse.

$('.collapser').click(function() {
    $(this).next().collapse('toggle');
});

Example jsFiddle

发布评论

评论列表(0)

  1. 暂无评论