TL; DR当你有一架允许模特中有多件物品的手风琴时,我该如何处理这种情况?
我有一个支持Twitter Bootstrap的Rails应用程序,因此我尝试使用ERB设置几个手风琴面板以从模型中获取一些动态内容。这是我的application.js:
// This is a manifest file that'll be compiled into application.js, which will include all the files
// listed below.
//
// Any JavaScript/Coffee file within this directory, lib/assets/javascripts, vendor/assets/javascripts,
// or any plugin's vendor/assets/javascripts directory can be referenced here using a relative path.
//
// It's not advisable to add code directly here, but if you do, it'll appear at the bottom of the
// compiled file.
//
// Read Sprockets README (https://github.com/rails/sprockets#sprockets-directives) for details
// about supported directives.
//
//= require jquery
//= require jquery_ujs
//= require bootstrap-sprockets
//= require turbolinks
//= require_tree .
最重要的是,我希望手风琴可以单独渲染每个手风琴。这是我的index.html.erb:
<div class="container">
<h1>Showing all <%= @courses.count %> courses</h1>
<% if @courses.present? %>
<% @courses.each do |course| %>
<%= link_to course.name, course_path(course) %>
<div class="panel-group" id="accordion" role="tablist" aria-multiselectable="true">
<div class="panel panel-default">
<div class="panel-heading" role="tab" id="headingOne">
<h4 class="panel-title">
<%= link_to course.name, '#collapseOne', 'role' => 'button', data: {toggle: 'collapse', parent: '#accordion' } %>
</h4>
</div>
<div id="collapseOne" class="panel-collapse collapse in" role="tabpanel" aria-labelledby="headingOne">
<div class="panel-body">
<%= render partial: 'courses/show', id: course %>
</div>
</div>
</div>
<% end %>
<% else %>
<p>You should create a course!</p>
<% end %>
<br><br>
<%= link_to "New Course", new_course_path %>
</div>
它只能让我折叠第一支手风琴而不是其他手风琴。我怎么能用手风琴来解决这个问题?
答案 0 :(得分:3)
在循环中,您为所有面板组使用相同的元素ID id="accordion"
:
<div class="panel-group" id="accordion" role="tablist" aria-multiselectable="true">
您应该为每次迭代分配动态ID。
<% @courses.each_with_index do |course, index| %>
<%= link_to course.name, course_path(course) %>
<div class="panel-group" id="accordion-<%= index %>" role="tablist" aria-multiselectable="true">
<%# Snipped for brevity %>