Rails通过单击按钮排序元素

Rails sort element by click a button

本文关键字:排序 元素 按钮 单击 Rails      更新时间:2023-09-26

场景:有一个排序按钮,当用户点击它时,列表将按name排序(之前是按created_at排序)

我有一个问题是,我做排序代码在ruby,但我怎么知道当用户点击按钮?

例如:

<button id = "sort_btn">Sort by name!</button>
...
<%# before_sort is origin array %>  
<% sort_arr = Array.new(before_sort) %>
<%# x[1] is the name attribute %>
<% sort_arr.sort_by!{|x| x[1]} %> 
<%# if click sort button %> 
<% sort_arr.each do |section_layer1| %>
<%# if did't click sort button or click twice sort button %>
<% before_sort.each do |section_layer1|>
    <%= render :partial => 'list', :locals => {:section => section_layer1 }%>
<% end %>

我想我可能会使用Javascript删除原始显示,并在用户单击排序按钮后再次呈现部分视图。

Javascript!您可以在单击

时手动添加get参数:
$(".sort_btn").on('click',function(){
  if (url.indexOf('?') > -1){
  url += "&sort=sort";
  }else{
  url += "?sort=sort";
  }
  }
  window.location.href = url;
  });

然后,如果参数存在,打印排序表:

<%- if params[:sort].present? %>
  -- print sorted table --
<%- else %>
  -- not sorted --
<% end %>