有没有办法使用 Ruby 或可能的 Rails 辅助方法将 HTML .class 添加到无序列表项?
基本上我只是在遍历待办事项模型
<ul>
<% @todos.each do |todo| %>
<li><%= todo.task %></li>
<% end %>
</ul>
我想将 class="third"添加到第三个列表项,这样 HTML 输出看起来像
<ul>
<li>Task 1</li>
<li>Task 2</li>
<li class="third">Task 3</li>
<ul>
我正在使用 jQuery 添加类,但我想要一种更好的方法来执行此操作,而不是依赖 javascript。
谢谢大家。
最佳答案
一种方法是使用 each_with_index (索引从零开始):
<ul>
<% @todos.each_with_index do |todo,index| %>
<li<%= ' class="third"' if index == 2 %>><%= todo.task %></li>
<% end %>
</ul>
关于ruby - 在 Rails 3.2 中向 <ul> 添加一个类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12038726/