【问题标题】:What is the simplest way to allow a user to drag and drop table rows in order to change their order?允许用户拖放表格行以更改其顺序的最简单方法是什么?
【发布时间】:2010-09-15 03:07:25
【问题描述】:

我正在编写一个 Ruby on Rails 应用程序,用户可以选择编辑发票。他们需要能够重新分配行的顺序。现在我在数据库中有一个索引列,用作默认排序机制。我只是公开了它并允许用户对其进行编辑。

这不是很优雅。我希望用户能够拖放表格行。我使用过一些 Scriptaculous 和 Prototype 并且对它们很熟悉。我已经完成了拖放列表,但还没有像这样完成表格行。有人对不仅重新排序而且有效地捕获重新排序有任何建议吗?

此外,用户现在可以在 JS 中动态创建新行,因此该行也必须是可重新排序的。

如果可以使用 RJS 而不是直接 JavaScript 来完成,则可以加分。

【问题讨论】:

  • 2.5 年后,不知道这个问题目前的答案是什么?

标签: html ruby-on-rails ajax


【解决方案1】:

我以前使用 Yahoo 用户界面库来执行此操作:

http://developer.yahoo.com/yui/dragdrop/

【讨论】:

    【解决方案2】:

    MooTools sortables 实际上比script.aculo.us 更好,因为它们是动态的; MooTools 允许向列表中添加/删除项目。将新项目添加到 script.aculo.us 可排序时,您必须销毁/重新创建可排序以使新项目可排序。如果列表有很多元素,这样做会产生很多开销。由于这个限制,我不得不从 script.aculo.us 切换到更轻量级的 MooTools,并最终对这个决定非常满意。

    MooTools 使新添加的项目可排序的方法是:

    sortables.addItems(node);
    

    【讨论】:

    • 老实说,我喜欢 MooTools。它不像其他的那样被广泛使用,但图书馆很棒!
    【解决方案3】:

    好的,我做了更多的搜索,发现了一些似乎主要工作的东西。

    edit.html.erb:

    ...
    <table id="invoices">
       <thead>
         <tr>
          <th>Id</th>
          <th>Description</th>
         </tr>
       </thead>
       <tbody id="line_items">
          <%= render :partial => 'invoice_line_item', :collection => @invoice.invoice_line_items.sort %>
       </tbody>
    </table>
    
    <%= sortable_element('line_items', {:url => {:action => :update_index}, :tag => :tr, :constraint => :vertical}) -%>
    ...
    

    app/controllers/invoices.rb

    ...
    def update_index
      params["line_items"].each_with_index do |id, index|
        InvoiceLineItem.update(id, :index => index)
      end
      render :nothing => true
    end
    ...
    

    重要的部分是 "sortable_element" 和 params["line_items"] 中的 :tag => :tr -- 这给出了新的 id 列表并在放置时触发。

    缺点:使 AJAX 调用下降,我想我更喜欢存储订单并在用户点击“保存”时更新。未经 IE 测试。

    【讨论】:

      【解决方案4】:

      我喜欢 jQuery http://docs.jquery.com/UI/Sortables

      $("#myList").sortable({});

      您需要编写一些代码来持久化它,但这并不难。

      【讨论】:

        【解决方案5】:

        Yahoo 界面比我预期的要简单,不到四个小时就完成了一些时髦的工作。

        【讨论】:

          【解决方案6】:

          Scriptaculous sortables 似乎是内置的方法。 http://github.com/madrobby/scriptaculous/wikis/sortable

          【讨论】:

            【解决方案7】:

            使用PrototypeScriptaculous

            Sortable.create('yourTable', {
                tag: 'tr',
                handles: $$('a.move'),
                onUpdate: function() {
                    console.log('onUpdate');
                }
            });
            

            【讨论】:

              猜你喜欢
              • 1970-01-01
              • 2011-01-05
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 2012-10-11
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              相关资源
              最近更新 更多