这是另一个解决方案:
/**
* Make an accordion active
* @param {String} id ID of the accordion
*/
var activateAccordion = function (id) {
// Get the parents
var parents = $('a[href="#' + id + '"]').parents('.panel-group').children('.panel');
// Go through each of the parents
$.each(parents, function (idx, obj) {
// Check if the child exists
var find = $(obj).find('a[href="#' + id + '"]'),
children = $(obj).children('.panel-collapse');
if (find.length > 0) {
// Show the selected child
children.removeClass('collapse');
children.addClass('in');
} else {
// Hide the others
children.removeClass('in');
children.addClass('collapse');
}
});
};
代码的重要部分是组合,记住.collapse类,而不仅仅是使用.in:
// Show the selected child
children.removeClass('collapse');
children.addClass('in');
和
// Hide the others
children.removeClass('in');
children.addClass('collapse');
上面的例子已经在 Twitter 的 Bootstrap v3.3.4 中测试过了