javascript - Codeigniter 中可扩展表内的表排序问题

标签 javascript php jquery codeigniter tableview

我想在可扩展表格 View 中对表格数据进行排序,所以我尝试了以下代码:

Code Link

我的观点如下图所示 enter image description here

当我使用此代码并将其放入我的网站时,它在这种类型的 View (如可扩展表格 View )中不起作用。未在可扩展 TableView 中执行排序。知道如何让它发挥作用吗?

编辑

stupidtable.js

// Stupid jQuery table plugin.

 (function($) {
 $.fn.stupidtable = function(sortFns) {
 return this.each(function() {
  var $table = $(this);
  sortFns = sortFns || {};
  sortFns = $.extend({}, $.fn.stupidtable.default_sort_fns, sortFns);
  $table.data('sortFns', sortFns);

  $table.on("click.stupidtable", "thead th", function() {
      $(this).stupidsort();
   });
  });
};


 // Expects $("#mytable").stupidtable() to have already been called.
 // Call on a table header.
 $.fn.stupidsort = function(force_direction){
 var $this_th = $(this);
 var th_index = 0; // we'll increment this soon
 var dir = $.fn.stupidtable.dir;
 var $table = $this_th.closest("table");
 var datatype = $this_th.data("sort") || null;

 // No datatype? Nothing to do.
 if (datatype === null) {
  return;
 }

// Account for colspans
$this_th.parents("tr").find("th").slice(0, $(this).index()).each(function()       {
  var cols = $(this).attr("colspan") || 1;
  th_index += parseInt(cols,10);
});

var sort_dir;
if(arguments.length == 1){
    sort_dir = force_direction;
}
else{
    sort_dir = force_direction || $this_th.data("sort-default") || dir.ASC;
    if ($this_th.data("sort-dir"))
       sort_dir = $this_th.data("sort-dir") === dir.ASC ? dir.DESC : dir.ASC;
}


$table.trigger("beforetablesort", {column: th_index, direction: sort_dir});

// More reliable method of forcing a redraw
$table.css("display");

// Run sorting asynchronously on a timout to force browser redraw after
// `beforetablesort` callback. Also avoids locking up the browser too much.
setTimeout(function() {
  // Gather the elements for this column
  var column = [];
  var sortFns = $table.data('sortFns');
  var sortMethod = sortFns[datatype];
  var trs = $table.children("tbody").children("tr");

  // Extract the data for the column that needs to be sorted and pair it up
  // with the TR itself into a tuple. This way sorting the values will
  // incidentally sort the trs.
  trs.each(function(index,tr) {
    var $e = $(tr).children().eq(th_index);
    var sort_val = $e.data("sort-value");

    // Store and read from the .data cache for display text only sorts
    // instead of looking through the DOM every time
    if(typeof(sort_val) === "undefined"){
      var txt = $e.text();
      $e.data('sort-value', txt);
      sort_val = txt;
    }
    column.push([sort_val, tr]);
  });

  // Sort by the data-order-by value
  column.sort(function(a, b) { return sortMethod(a[0], b[0]); });
  if (sort_dir != dir.ASC)
    column.reverse();

  // Replace the content of tbody with the sorted rows. Strangely
  // enough, .append accomplishes this for us.
  trs = $.map(column, function(kv) { return kv[1]; });
  $table.children("tbody").append(trs);

  // Reset siblings
  $table.find("th").data("sort-dir", null).removeClass("sorting-desc sorting-asc");
  $this_th.data("sort-dir", sort_dir).addClass("sorting-"+sort_dir);

  $table.trigger("aftertablesort", {column: th_index, direction: sort_dir});
  $table.css("display");
}, 10);

return $this_th;
 };

  // Call on a sortable td to update its value in the sort. This should be the
  // only mechanism used to update a cell's sort value. If your display value is
 // different from your sort value, use jQuery's .text() or .html() to update
 // the td contents, Assumes stupidtable has already been called for the table.
 $.fn.updateSortVal = function(new_sort_val){
 var $this_td = $(this);
 if($this_td.is('[data-sort-value]')){
  // For visual consistency with the .data cache
  $this_td.attr('data-sort-value', new_sort_val);
  }
 $this_td.data("sort-value", new_sort_val);
 return $this_td;
};

 // ------------------------------------------------------------------
  // Default settings
 // ------------------------------------------------------------------
 $.fn.stupidtable.dir = {ASC: "asc", DESC: "desc"};
 $.fn.stupidtable.default_sort_fns = {
"int": function(a, b) {
  return parseInt(a, 10) - parseInt(b, 10);
},
"float": function(a, b) {
  return parseFloat(a) - parseFloat(b);
},
 "string": function(a, b) {
  return a.localeCompare(b);
}, 
"string-ins": function(a, b) {
  a = a.toLocaleLowerCase();
  b = b.toLocaleLowerCase();
  return a.localeCompare(b);
 }
 };
 })(jQuery);

我的脚本代码

 <script>
$(function(){
    // Helper function to convert a string of the form "Mar 15, 1987" into a Date object.
    var date_from_string = function(str) {
      var months = ["jan","feb","mar","apr","may","jun","jul","aug","sep","oct","nov","dec"];
      var pattern = "^([a-zA-Z]{3})\\s*(\\d{1,2}),\\s*(\\d{4})$";
      var re = new RegExp(pattern);
      var DateParts = re.exec(str).slice(1);

      var Year = DateParts[2];
      var Month = $.inArray(DateParts[0].toLowerCase(), months);
      var Day = DateParts[1];

      return new Date(Year, Month, Day);
    }

    var table = $("table").stupidtable({
      "date": function(a,b) {
        // Get these into date objects for comparison.
        aDate = date_from_string(angel);
        bDate = date_from_string(beer);
        return aDate - bDate;
      }
    });

    table.on("beforetablesort", function (event, data) {
      // Apply a "disabled" look to the table while sorting.
      // Using addClass for "testing" as it takes slightly longer to render.
      $("#msg").text("Sorting...");
      $("table").addClass("disabled");
    });

    table.on("aftertablesort", function (event, data) {
      // Reset loading message.
      $("#msg").html("&nbsp;");
      $("table").removeClass("disabled");

      var th = $(this).find("th");
      th.find(".arrow").remove();
      var dir = $.fn.stupidtable.dir;

      var arrow = data.direction === dir.ASC ? "&uarr;" : "&darr;";
      th.eq(data.column).append('<span class="arrow">' + arrow +'</span>');
    });
  });
</script>

当我运行上面的代码并展开 View 时,在我的 stupidtable.js 文件中,有类似

的代码
"string": function(a, b) {
  return a.localeCompare(b);
},  

在此代码中,a.localeCompare(b); 在可扩展 TableView 中获取 null,因此它不能很好地排序,而且我还想在扩展表的数据内进行排序。知道如何解决这个问题吗?

html代码

<table id="property" class="hometable table-bordered">
                      <thead>
                        <tr>
                          <th >#</th>
                          <th  >Image</th>
                          <th width="12%" >
                            <a href="<?php echo base_url();?>property/propertylist?field=p_name&sort_by=<?php echo $sort;?>">
                              Property Name &nbsp;
                              <? if($sort == 'ASC' && $_GET['field']=='p_name') echo '<img src='.base_url("assets/plugins/data-tables/images/sort_asc.png").'>'; else if($sort == 'DESC'&& $_GET['field']=='p_name') { echo '<img src='.base_url("assets/plugins/data-tables/images/sort_desc.png").'>';  } else {echo '<img src='.base_url("assets/plugins/data-tables/images/sort_both.png").'>';}?>
                            </a>
                          </th>
                          <th >Address</th>
                          <th >
                            <a href="<?php echo base_url();?>property/propertylist?field=p_city&sort_by=<?php echo $sort;?>">
                              City &nbsp;
                              <? if($sort == 'ASC' && $_GET['field']=='p_city') echo '<img src='.base_url("assets/plugins/data-tables/images/sort_asc.png").'>'; else if($sort == 'DESC' && $_GET['field']=='p_city') { echo '<img src='.base_url("assets/plugins/data-tables/images/sort_desc.png").'>';  } else {echo '<img src='.base_url("assets/plugins/data-tables/images/sort_both.png").'>';}?>
                            </a>
                          </th>
                          <th >
                            <a href="<?php echo base_url();?>property/propertylist?field=p_state&sort_by=<?php echo $sort;?>">
                              State &nbsp;
                              <? if($sort == 'ASC' && $_GET['field']=='p_state') echo '<img src='.base_url("assets/plugins/data-tables/images/sort_asc.png").'>'; else if($sort == 'DESC' && $_GET['field']=='p_state') { echo '<img src='.base_url("assets/plugins/data-tables/images/sort_desc.png").'>';  } else {echo '<img src='.base_url("assets/plugins/data-tables/images/sort_both.png").'>';}?>
                            </a>
                          </th>
                          <th width="9%" >
                            <a href="<?php echo base_url();?>property/propertylist?field=p_country&sort_by=<?php echo $sort;?>">
                              Country &nbsp;
                              <? if($sort == 'ASC' && $_GET['field']=='p_country') echo '<img src='.base_url("assets/plugins/data-tables/images/sort_asc.png").'>'; else if($sort == 'DESC' && $_GET['field']=='p_country') { echo '<img src='.base_url("assets/plugins/data-tables/images/sort_desc.png").'>';  } else {echo '<img src='.base_url("assets/plugins/data-tables/images/sort_both.png").'>';}?>
                            </a>
                          </th>
                          <th >Zipcode</th>
                          <th colspan="2" >
                            <a href="<?php echo base_url();?>property/propertylist?field=unit_type&sort_by=<?php echo $sort;?>">
                              Property Type &nbsp;
                              <? if($sort == 'ASC' && $_GET['field']=='unit_type') echo '<img src='.base_url("assets/plugins/data-tables/images/sort_asc.png").'>'; else if($sort == 'DESC' && $_GET['field']=='unit_type') { echo '<img src='.base_url("assets/plugins/data-tables/images/sort_desc.png").'>';  } else {echo '<img src='.base_url("assets/plugins/data-tables/images/sort_both.png").'>';}?>
                            </a>
                          </th>
                          <th >Tenants</th>
                          <? if(!empty($query1)){?>
                          <th >Edit </th>
                          <th >Copy </th>
                          <th >Delete </th>
                          <? } else {?>
                          <th >Edit </th>
                          <th >Copy</th>
                          <th >Delete</th>
                          <? } ?>
                        </tr>
                      </thead>
                      <?  if(empty($detail)) {  ?>
                      <tr>
                        <td colspan="14">
                          <div class="tblalert alert-danger"><!--<button class="close" data-close="alert"></button>--><span>No property available.</span></div>
                        </td>
                      </tr>
                      <?php }else {
            $i = 0;
            foreach($detail as $pro) {  

                    $i++;
        ?>
                      <tr id="trarrow<? echo $i;?>">
                        <? $admindata = $this->session->userdata('id');
     $query = $this->db->query('SELECT r_country,amt_format FROM register where id="'.$admindata.'"');
              foreach ($query->result() as $row)
              {     $currency = $row->r_country ;
                    $amt_format = $row->amt_format ;
              }
               $curren = $this->db->query('SELECT * FROM country where id="'.$currency.'"');
              foreach ($curren->result() as $row)
              {     $curr = $row->currency ;

              }

              $unit = $this->db->query("SELECT * FROM property_unit WHERE p_id = '".$pro['p_id']."'");
              $unitid = count($unit->result_array());
       ?>
                        <?php /*?><?php if($pro['unit_type'] == '0'){ ?>
       <td align="center"   style="cursor:pointer"><div class="arrow" id="arimg<?php  echo $i?>"></div></td>
       <? } else {?>
                     <td align="center" id="arrow<?php  echo $i?>" onClick="trshow(<?php  echo $i?>);" style="cursor:pointer"><div class="arrow" id="arimg<?php  echo $i?>"></div></td>

         <? } ?><?php */?>
                        <td><?php echo $i; ?></td>
                        <td align="center">
                          <?  if(!empty($pro['p_path'])) {  ?>
                          <a class="fancybox fancyboxiframe" href="<?php echo base_url('property/popup/'.$pro['p_id']);?>">
                            <img class="img-polaroid" src="http://worldofrental.s3.amazonaws.com/<? echo $pro['p_path'];?>" alt="Please Upload Image" width="50" height="50">
                            <? } else {?>
                            <img class="img-polaroid" src=<? echo base_url('upload/tenants/app_logo.png');?> alt="Upload Image" width="50" height="50">
                            <? } 


               ?>
                          </a>
                        </td>
                        <td >
                          <a href="<? echo base_url('property/propertyedit/'.$pro['p_id']);?>">
                            <?php echo $pro['p_name']; ?>
                          </a>
                        </td>
                        <td ><?php echo $pro['p_address']; ?></td>
                        <td><?php echo $pro['p_city']; ?></td>
                        <td>
                          <?php $statename =  $this->db->query("SELECT state_name FROM state WHERE state_id = '".$pro['p_state']."'"); $state_name = $statename->result_array(); echo $state_name[0]['state_name']; ?>
                        </td>
                        <td ><?php echo $pro['name']; ?></td>
                        <td><?php echo $pro['p_zipcode']; ?></td>
                        <?php if($pro['unit_type'] == '0'){ ?>
                        <td style="border-right:solid 0px !important; "></td>
                        <td align="right" style="border-left:solid 0px !important; "><?php echo 'Single Unit'; ?></td>
                        <? } else {?>
                        <td style="border-right:solid 0px !important; cursor:pointer; " id="arrow<?php  echo $i?>" onClick="trshow(<?php  echo $i?>);" >
                          <div class="arrow" id="arimg<?php  echo $i?>"></div>
                        </td>
                        <td align="right" style="cursor:pointer; border-left:solid 0px !important; " id="arrow<?php  echo $i?>" onClick="trshow(<?php  echo $i?>);" >
                          <div id="arimg<?php  echo $i?>"></div>
                          <a class="btn default btn-xs blue" >
                            <? echo 'Multi Unit' .'&nbsp;'.'('.$unitid.')';?>
                          </a>
                          <? } ?>
                          </a>
                        </td>
                        <td>
                          <a class="btn default btn-xs yellow" data-toggle="modal" onClick="Viewtenants(<? echo $pro['p_id'];?>); return false;" title="View Tenants" href="#myproperty-<? echo $pro['p_id'];?>">
                            View Tenants
                          </a>
                        </td>
                        <div id="myproperty-<? echo $pro['p_id'];?>" class="modal fade"></div>
                        <? if(!empty($query1)){?>
                        <td>
                          <a class="btn blue disabled" title="your service has been canceled" href="<?php echo base_url('property/propertyedit/'.$pro['p_id']);?>">
                            <i class="fa fa-edit"></i> Edit
                          </a>
                        </td>
                        <div id="myModal-<? //echo $pro->pid;?>" class="modal fade"></div>
                        <td>
                          <a class="btn green disabled" title="your service has been canceled" href="<?php echo base_url('property/copydata/'.$pro['p_id']);?>">
                            <i class="fa fa-copy"></i> Copy
                          </a>
                        </td>
                        <!--<td class="status" align="center"><a style="cursor:pointer" title="Trash" onClick="CheckUsername(<? echo $pro['p_id'];?>); return false;" id="status">
              <div id="status-<? echo $pro['p_id'];?>"> 
                                </div>  <i class="fa fa-trash-o"></i> Trash</a></td>-->
                        <td>
                          <a class="delete btn red disabled btn-xs black delete-confirm" delete-url="<?php echo base_url('property/status_change/'.$pro['p_id']);?>" data-confirm="Are you sure you want to trash this property?" title="your service has been canceled">
                            <i class="fa fa-trash-o"></i> Delete
                          </a>
                        </td>
                        <? } else {?>
                        <td>
                          <a  class="btn default btn-xs blue" title="Edit/View" href="<?php echo base_url('property/propertyedit/'.$pro['p_id']);?>">
                            <i class="fa fa-edit"></i> Edit
                          </a>
                        </td>
                        <div id="myModal-<? //echo $pro->pid;?>" class="modal fade"></div>
                        <td align="center">
                          <a class="btn default btn-xs green" title="Edit/View" href="<?php echo base_url('property/copydata/'.$pro['p_id']);?>">
                            <i class="fa fa-copy"></i> Copy
                          </a>
                        </td>
                        <td>
                          <a class="btn red" data-toggle="modal" onClick="ViewStore(<? echo $pro['p_id'];?>); return false;" title="Delete" href="#myModal-<? echo $pro['p_id'];?>">
                            <i class="fa fa-trash-o"></i>
                            <font size="-1"> Delete</font>
                          </a>
                        </td>
                        <div id="myModal-<? echo $pro['p_id'];?>" class="modal fade"></div>
                        <? } ?>
                      </tr>
                      <tr id="subtr<?php echo $i; ?>">
                        <td colspan="14">
                          <? $unit_info = $this->db->query("SELECT * FROM unit_info WHERE p_id = '".$pro['p_id']."' AND isactive = '0' AND unit_id <> '0'");
                            $result = $unit_info->result_array();
                            ?>
                          <? if(empty($result)) {?>
                          <? }else{ ?>
                          <div class="propertyreport-box">
                            <div class="title">Property Units</div>
                            <ul class="finacial-list">
                              <li><strong>Unit Name</strong></li>
                              <? foreach($unit_info->result() as $unit){?>
                              <li><span>
                                <? $unitname = $this->db->query("SELECT unit_name FROM property_unit WHERE unit_id = '".$unit->unit_id."'"); $unit_name = $unitname->result_array();   echo $unit_name[0]['unit_name'] ;?>
                                </span></li>
                              <? } ?>
                            </ul>
                            <ul class="finacial-list">
                              <li><strong>Rent </strong></li>
                              <? foreach($unit_info->result() as $unit){?>
                              <li><span>
                                <? if(!empty($unit->p_rent)){ echo $curr.' '.$unit->p_rent;}else { echo $curr.' '.'0.00';}?>
                                </span></li>
                              <? } ?>
                            </ul>
                            <ul class="finacial-list">
                              <li><strong>Bedrooms</strong></li>
                              <? foreach($unit_info->result() as $unit){?>
                              <li><span>
                                <? if(!empty($unit->p_bedroom)){ echo $unit->p_bedroom; }else { echo '0.0';}?>
                                </span></li>
                              <? } ?>
                            </ul>
                            <ul class="finacial-list">
                              <li><strong>Bathrooms</strong></li>
                              <? foreach($unit_info->result() as $unit){?>
                              <li><span>
                                <? if(!empty($unit->p_bathroom)){ echo $unit->p_bathroom; }else { echo '0.0';}?>
                                </span></li>
                              <? } ?>
                            </ul>
                            <ul class="finacial-list">
                              <li><strong>Sq. Ft</strong></li>
                              <? foreach($unit_info->result() as $unit){?>
                              <li><span>
                                <? if(!empty($unit->p_size)){ echo $unit->p_size; }else { echo '0.00';}?>
                                </span></li>
                              <? } ?>
                            </ul>
                            <ul class="finacial-list">
                              <li><strong>Rented</strong></li>
                              <? foreach($unit_info->result() as $unit){?>
                              <li><span><? echo $unit->p_isrent;?></span></li>
                              <? } ?>
                            </ul>
                            <ul class="finacial-list">
                              <li><strong>Tenants</strong></li>
                              <? foreach($unit_info->result() as $unit){?>
                              <li><span>
                                <a class="btn btn-xs yellow" data-toggle="modal" onClick="viewunittenants(<? echo $unit->unit_info_id;?>); return false;" title="Delete" href="#myproperty-<? echo $unit->unit_info_id;?>">
                                  <font size="-2"> View Tenants</font>
                                </a>
                                </span></li>
                              <div id="myproperty-<? echo $unit->unit_info_id;?>" class="modal fade "></div>
                              <? } ?>
                            </ul>
                            <ul class="finacial-list">
                              <li><strong>Edit</strong></li>
                              <? foreach($unit_info->result() as $unit){?>
                              <li><span>
                                <a class="btn btn-xs yellow" title="Edit/View" href="<?php echo base_url('unit/unitedit/'.$unit->unit_info_id);?>">
                                  <i class="fa fa-edit"></i>
                                  <font size="-2"> Edit</font>
                                </a>
                                </span></li>
                              <? } ?>
                            </ul>
                            <ul class="finacial-list">
                              <li><strong>Delete</strong></li>
                              <? foreach($unit_info->result() as $unit){?>
                              <li><span>
                                <a class="btn btn-xs dark" data-toggle="modal" onClick="ViewStore1(<? echo $unit->unit_info_id;?>); return false;" title="Delete" href="#myModal1-<? echo $unit->unit_info_id;?>">
                                  <i class="fa fa-trash-o"></i>
                                  <font size="-2"> Delete</font>
                                </a>
                                </span></li>
                              <div id="myModal1-<? echo $unit->unit_info_id;?>" class="modal fade "></div>
                              <? } ?>
                            </ul>
                          </div>
                          <? } ?>
                        </td>
                      </tr>
                      <?php
} }
?>
                    </table>

最佳答案

您只需尝试 Bootstrap 数据表

Click the link

关于javascript - Codeigniter 中可扩展表内的表排序问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30480333/

相关文章:

javascript - 未捕获的类型错误 : Cannot read property 'mouseX' of undefined

javascript - 将具有相同属性的对象分组 - javascript

php - 将表单变量传递到 Php 查询

javascript - 循环遍历 JSON 数组不起作用

javascript - 定位在绝对定位的 div 下方

javascript - JavaScript 命名空间和事件监听器中的 "this"问题

javascript - Ajax获取列表值成为javascript中的变量

php - 如何解释 mysql 文本字段中的换行符?

php - 将对象推送到rabbitMQ队列上

javascript - 如何在 EL 表达式中使用 JavaScript (ui :param with value)