jQuery表排序器不能处理由AJAX获取的值


jQuery table sorter not working for values that are fetched by AJAX

我已经在我的项目中实现了jQuery tablesorter。

我的表由输入文本字段组成,其中一些由ajax填充。对于用户输入的输入字段,表排序工作得很好,但是使用ajax从数据库填充的输入字段不能正确排序。

我的代码:
jQuery(function () {
    jQuery('#tablesorter-demo').tablesorter({
        widgets: ['zebra', 'stickyHeaders'],
        headers: {
            2: {
                sorter: 'inputs'
            },
            3: {
                sorter: 'inputs'
            },
            5: {
                sorter: 'inputs'
            }
        }
    });
});
jQuery.tablesorter.addParser({
    id: 'inputs',
    is: function (s) {
        return false;
    },
    format: function (s, table, cell, cellIndex) {
        var jQueryc = jQuery(cell);
        // return 1 for true, 2 for false, so true sorts before false
        if (!jQueryc.hasClass('updateInput')) {
            jQueryc
                .addClass('updateInput')
                .bind('keyup', function () {
                    console.log(table);
                    jQuery(table).trigger('updateCell', [cell, false]); // false to prevent resort
                });
        }
        return jQueryc.find('input[type="text"]').val();
    },
    type: 'text'
});
我的AJAX函数:
jQuery('.bulkupload').keyup(function () {
    check = 1;
    jQuery("#" + jQuery(this).attr("id")).css("color", "#928F8F");
    var part_no1 = jQuery("#" + jQuery(this).attr("id")).val();
    var fieldcount = part_no1.toString().length;
    var thenum = jQuery(this).attr("id").replace(/^'D+/g, '');
    if (jQuery('#qty' + thenum).val() == '') {
        jQuery('#qty' + thenum).val('Enter Quantity');
        jQuery('#qty' + thenum).css("color", "#DF1F26");
    }
    var url1 = "<?php echo Mage::getBaseUrl(); ?>availableorders/index/getdetails";
    jQuery.ajax({
        type: "POST",
        url: url1,
        data: {
            part_no1: part_no1
        },
        success: function (response) {
            if (response == "check") {
                jQuery('#item_name' + thenum).val("Not Found");
                jQuery('#item_desc' + thenum).val("Not Found");
                jQuery('#av_qty' + thenum).css("color", "#DF1F26");
                jQuery('#item_name' + thenum).css("color", "#DF1F26");
                jQuery('#item_desc' + thenum).css("color", "#DF1F26");
                jQuery('#brand_name' + thenum).css("color", "#DF1F26");
            } 
            else {
                var result1 = jQuery.parseJSON(response);
                jQuery('#item_name' + thenum).val(result1.prodname1);
                jQuery('#item_desc' + thenum).val(result1.productdescription1);
                jQuery('#brand_name' + thenum).val(result1.brand);
                jQuery('#av_qty' + thenum).css("color", "#DF1F26");
                jQuery('#item_name' + thenum).css("color", "#DF1F26");
                jQuery('#item_desc' + thenum).css("color", "#DF1F26");
                jQuery('#brand_name' + thenum).css("color", "#DF1F26");
                if (jQuery('#av_qty' + thenum).val(result1.stock) == 0) {
                    jQuery('#av_qty' + thenum).val("Not in Stock");
                } else {
                    jQuery('#av_qty' + thenum).val(result1.stock);
                }
                jQuery("#tablesorter-demo").trigger('updateCell');
            }
        }
    });
});

从选项&你正在使用的小部件,看起来你实际上是在使用我的叉子而不是原来的插件。

无论如何,您为输入解析器创建的小部件绑定到单元格
jQuery(cell).bind('keyup', function () { ... }

,但是当对表进行排序时,单元格将从表体中删除,从而导致任何事件绑定中断。解决这个问题的方法是在主体上使用委托事件绑定(但是在小部件format函数之外完成,因为只需要完成一次)。

jQuery('table tbody').on('keyup', 'input', function(e) {
    var $input = $(e.target);
    ...
}

另外,当你从ajax调用中更新大量输入时,最好一次更新它们(.trigger('update')),否则你使用updateCell方法太多,可能导致整个过程花费比必要的时间更长。

这个演示使用了一个非常相似的方法来更新表中的复选框,所以转换它使它与输入值一起工作应该是相当直接的-如果你有问题,只要在这里发布,我会帮助你。

// checkbox parser
$.tablesorter.addParser( {
    id: 'checkbox',
    is: function( s ) {
        return false;
    },
    format: function( s, table, cell ) {
        var $c = $( cell ).find( 'input' );
        return $c.length ? $c.is( ':checked' ) ? 1 : 2 : s;
    },
    type: 'numeric'
});
$( function() {
    // using .on() which requires jQuery 1.7+
    $( 'table' ).on( 'tablesorter-initialized', function() {
        // class name to add on tr when checkbox is checked
        var highlightClass = 'checked',
        // resort the table after the checkbox is modified?
        resort = true,
        // if a server side database needs to be updated, do it here
        serverCallback = function( table, inputElement ) {},
        $table = $( this ),
        c = this.config,
        wo = c && c.widgetOptions,
        // include sticky header checkbox; if installed
        $sticky = c && wo.$sticky || '',
        doChecky = function( c, col ) {
            $table
                .children( 'tbody' )
                .children( 'tr:visible' )
                .children( 'td:nth-child( ' + ( parseInt( col, 10 ) + 1 ) + ' )' )
                .find( 'input' )
                .each( function() {
                    this.checked = c;
                    $( this ).trigger( 'change' );
                });
        };
        $table
            .children( 'tbody' )
            .on( 'change', 'input', function() {
                // ignore change if updating all rows
                if ( $table[0].ignoreChange ) { return; }
                var col, $this = $( this );
                $this.closest( 'tr' ).toggleClass( highlightClass, this.checked );
                $this.trigger( 'updateCell', [ $this.closest( 'td' ), resort ] );
                // if your server side database needs more parameters, add them here sent to the callback
                serverCallback( $table[0], this );
                // uncheck header if any checkboxes are unchecked
                if ( !this.checked ) {
                    $table.add( $sticky ).find( 'thead input' ).prop( 'checked', false );
                }
            })
            .end()
            .add( $sticky )
            .find( 'thead input' )
            // Click on checkbox in table header to toggle all inputs
            .on( 'change', function() {
                // prevent updateCell for every cell
                $table[0].ignoreChange = true;
                var c = this.checked,
                    col = $( this ).closest( 'th' ).attr( 'data-column' );
                doChecky( c, col );
                // update main & sticky header
                $table.add( $sticky ).find( 'th[data-column=' + col + '] input' ).prop( 'checked', c );
                $table.children( 'tbody' ).children( 'tr:visible' ).toggleClass( highlightClass, c );
                // update all at once
                $table[0].ignoreChange = false;
                $table.trigger( 'update', [ resort ] );
            })
            .on( 'mouseup', function() {
                return false;
            });
    });
});

我还应该注意到,当ajax调用完成并应用更改时,应该触发"update"方法,而不是"updateCell"。

最后,有一个现有的input-select parser,但它不包括一个方法来防止大量的updateCell方法调用,而不是一次更新表。

表排序对于输入字段是完美的由用户输入,但输入字段是从数据库中填充的使用ajax不能正确排序。

这是因为当你加载那个页面时,jQuery库&此时将加载表排序器库,并将表排序器功能添加到表中。

tablesorter-demo

示例如下:

<script type="text/javascript" src="/path/to/jquery-latest.js"></script> 
<script type="text/javascript" src="/path/to/jquery.tablesorter.js"></script> 
$(document).ready(function() 
    { 
        $("#tablesorter-demo").tablesorter(); 
    } 
); 

当内容通过AJAX加载时,这个表排序属性已经被添加到表&它不应用于AJAX函数获取的新数据,因为AJAX函数在初始页面加载后才工作。你只需要添加table sorter属性

$ (" # tablesorter-demo ") .tablesorter ();

刚好在

上方

jQuery("# tablesorter-demo").trigger (updateCell);

我希望这有助于..因为它为我工作,当我面临同样的问题,而通过AJAX加载内容&试着给它们排序

试试这个…

jQuery('.bulkupload').keyup(function () {
    check = 1;
    jQuery("#" + jQuery(this).attr("id")).css("color", "#928F8F");
    var part_no1 = jQuery("#" + jQuery(this).attr("id")).val();
    var fieldcount = part_no1.toString().length;
    var thenum = jQuery(this).attr("id").replace(/^'D+/g, '');
    if (jQuery('#qty' + thenum).val() == '') {
        jQuery('#qty' + thenum).val('Enter Quantity');
        jQuery('#qty' + thenum).css("color", "#DF1F26");
    }
 var url1 = "<?php echo Mage::getBaseUrl(); ?>availableorders/index/getdetails";
    ajaxfunction(url1);
    function ajaxfunction(url1)
    {
        if(window.XMLHttpRequest)
        {
            xmlhttp=new XMLHttpRequest();
        }
        else
        {
            xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
        }
        xmlhttp.onreadystatechange=function()//callback fn
        {
            if(xmlhttp.readyState==4 && xmlhttp.status==200)
            {
                var response=xmlhttp.responseText;
                if (response == "check") {
                    jQuery('#item_name' + thenum).val("Not Found");
                    jQuery('#item_desc' + thenum).val("Not Found");
                    jQuery('#av_qty' + thenum).css("color", "#DF1F26");
                    jQuery('#item_name' + thenum).css("color", "#DF1F26");
                    jQuery('#item_desc' + thenum).css("color", "#DF1F26");
                    jQuery('#brand_name' + thenum).css("color", "#DF1F26");
                }
                else {
                    var result1 = jQuery.parseJSON(response);
                    jQuery('#item_name' + thenum).val(result1.prodname1);
                    jQuery('#item_desc' + thenum).val(result1.productdescription1);
                    jQuery('#brand_name' + thenum).val(result1.brand);
                    jQuery('#av_qty' + thenum).css("color", "#DF1F26");
                    jQuery('#item_name' + thenum).css("color", "#DF1F26");
                    jQuery('#item_desc' + thenum).css("color", "#DF1F26");
                    jQuery('#brand_name' + thenum).css("color", "#DF1F26");
                    if (jQuery('#av_qty' + thenum).val(result1.stock) == 0) {
                        jQuery('#av_qty' + thenum).val("Not in Stock");
                    } else {
                        jQuery('#av_qty' + thenum).val(result1.stock);
                    }
                    jQuery("#tablesorter-demo").trigger('updateCell');
                    $("#tablesorter-demo").tablesorter();
                }

            }
        }
        xmlhttp.open("GET",url1,true);
        xmlhttp.send();
    }
});