每当用户点击其链接并在另一列中显示时,我就会尝试从特定笔记本中检索笔记标题。请温柔地对待我,还是ruby / rails的新手。
我的static_controller.rb 中的
我的index.html.erb def index
@user = current_user
@notebooks = @user.notebooks
@notes_hash = @user.notes.group_by(&:notebook_id)
respond_to do |format|
format.html
format.js
end
end
显然,我做错了。<div id="notebooks-list">
<% @notebooks.each do |notebook| %>
<%= link_to notebook.description, "#", {:class => "notebook-link",
:remote => true, :data => notebook.id.to_json }%>
<% end %>
</div>
<div id="notes-list">
<script type="text/javascript">
$(".notebook-link").click(function() {
var id = this.getAttribute("data");
<%= notes = @notes_hash['id'] || [ ] %>
var notes = <%= notes.collect{ |a| a.id }.to_json %>
$("#notes-list").html(notes);
});
</script>
</div>
答案 0 :(得分:1)
伙计,这是一个糟糕的代码(
修复当前变体:
首先&lt;%= notes = @notes_hash ['id'] || []%&gt;将仅在脚本中输出注释值,因此将其修复为&lt;%notes = @notes_hash ['id'] || []%&gt;
接下来,每次单击.notebook-link时初始化notes变量,将其从当前例程中删除:
<div id="notes-list">
</div>
<script type="text/javascript">
(function() {
<% notes = @notes_hash['id'] || [ ] %>
var notes = <%= notes.collect{ |a| a.id }.to_json %>
$(".notebook-link").click(function() {
var id = $(this).getAttribute("data");
$("#notes-list").html(notes[id]); # notes[id] is just an object, you will probably wants to render it someway e.g. with JQ templates
});
})()
</script>
另一种方法是使用分组注释渲染隐藏的div,onClick例程只显示匹配的div:
<div id="notebooks-list">
<% @notebooks.each do |notebook| %>
<%= link_to notebook.description, "#", {:class => "notebook-link",
:remote => true, :data => notebook.id.to_json }%>
<% end %>
</div>
<% @notes_hash.each_pair do |nh_id, notes| %>
<div class="notes-list hidden" data="<%= nh_id %>">
<ul>
<% notes.each do |note|
<li><%= note. description %></li>
<% end %>
</ul>
</div>
<% end %>
<script type="text/javascript">
$(".notebook-link").click(function() {
$(".notes-list").hide().filter("[data=\"" + $(this).attr("data") + "\"]").show()
});
</script>