【问题标题】:How to conditionally apply jQuery Sortable UI widget to table (ASP.NET GridView)?如何有条件地将 jQuery 可排序 UI 小部件应用于表(ASP.NET GridView)?
【发布时间】:2011-07-26 08:55:33
【问题描述】:

我有以下代码将 jQuery UI 可排序插件应用于 ASP.NET 页面上的所有表(GridView),不包括每个表中的第一(标题)行:

function pageLoad() {
    $('table').sortable({
        items: 'tr:not(:first)',
        axis: 'y',
        scroll: true,
        start: startDrag, //store start position
        stop: stopDrag    //get end position, update database
    }).disableSelection();

但是,如果有不止一行(除了标题行),我只想将可排序应用于表格,否则拖放功能是多余的。

如何有条件地将上述内容仅应用于具有多个内容行的表格?谢谢。

【问题讨论】:

  • 这很棒,而且非常及时,因为我需要类似的东西。 2 个要补充的问题:1) startDrag 未定义。我假设我需要在代码隐藏中声明它,但是什么数据类型? 2)我正在使用它来允许用户根据“订单”列(int)来使用有序列表。有没有一种有效的方法可以将其保存回数据库?
  • 也许更好的问题是我如何阅读 gridview 中的新位置。当我交换项目 0 和 1 并阅读 gridview1.Rows[0].Cells[1].Text 它仍然显示原始项目。不知道如何阅读每个位置的排序后项目。
  • 您可以检查被删除元素的常规 jquery index(),或使用sortable.serialize() 导出完整位置状态:jqueryui.com/demos/sortable/#method-serialize
  • @nycdan 在下面看到我的回答。如何处理重新排序。
  • @James McCormack 再次感谢您的帮助:)

标签: jquery asp.net jquery-ui gridview jquery-ui-sortable


【解决方案1】:

jquery filter() 提供了一个解决方案。它允许您使用测试功能过滤一组匹配的元素。因此,以下代码仅将sortable 应用于具有多个数据行的表:

function pageLoad() {

    $('table').filter(function () {
                        return $('tr', this).length > 2;
                      })
              .sortable({
                 items: 'tr:not(:first)',
                 axis: 'y',
                 scroll: true,
                 start: startDrag, //store start position
                 stop: stopDrag    //get end position, update database
                 })
              .disableSelection();
}

【讨论】:

    【解决方案2】:

    针对上面 nydcan 的查询,startDrag 方法如下所示:

     function startDrag(event, ui) {
        var startIndex = ui.item.index();
        ui.item.data('startIndex', startIndex);
    }
    

    stopDrag 方法如下所示:

    function stopDrag(event, ui) {
        var startIndex = ui.item.data('startIndex');
        var endIndex = ui.item.index();
        if (startIndex != endIndex) {
            $.ajax({
                type: 'POST',
                url: '<%= ResolveUrl("~/MyPage.aspx/UpdateOrder") %>',
                contentType: 'application/json; charset=utf-8',
                data: "{ 'startIndex':'" + startIndex + "', 'endIndex':'" + endIndex + "'}",
                dataType: 'json',
                success: updateSuccess,
                error: updateError
            });
        }
    }
    

    然后我的页面上有一个 Web 方法 (VB.NET),如下所示:

    <System.Web.Services.WebMethod()>
    Public Shared Sub UpdateRulePriority(ByVal startIndex As Integer, ByVal endIndex As Integer)
    
        'Do stuff
    
    End Sub
    

    希望对您有所帮助。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-02-03
      • 1970-01-01
      • 1970-01-01
      • 2019-02-03
      • 1970-01-01
      • 2021-01-20
      相关资源
      最近更新 更多