开发者

Traverse Nested Tables in JQuery

Need: I want to convert the data in my table into a comma separated value.

Problem: A table cell may have another table. (e.g. Row1, Cell 3 contains a table) The script needs to run for nested tables and capture the column only once. Here it is capturing "Col 3" twice. The number of nested tables is not known. It should be a generic script.

Thank you.

my HTML file:

<html>
 <head>
  <script src="http://code.jquery.com/jquery-1.4.4.min.js" type="text/javascript"></script> 
 <script src="jquery.table2csv.0.1.1.min.js" type="text/javascript"></script> 
 <script type="text/javascript">
 jQuery(function() {
  jQuery("#tableone").table2csv({
   callback: function (csv) {
    //alert(csv);
   }
  });
 });
</script>
</head>
<body>
 <table id="tableone" style="width:100%;">
  <tbody>
   <tr>
    <td>
     <div >
      Col 1
     </div>
    </td>
    <td >
     <div >
      Col 2
     </div>
    </td>
    <td >
     <div >
      <table >
       <tbody>
        <tr>
         <td >
          Col 3
         </td>
        </tr>
       </tbody>
      </table>
     </div>
    </td>
   </tr>
   <tr >
    <td >
     <div >
      Data in Col 1
     </div>
    </td>
    <td >
     <div >
      Data in Col 2
     </div>
    </td>
    <td >
     <div >
      Data in Col 3
     </div>
    </td>
   </tr>
  </tbody>
 </table>
 </body>
</html>

jquery.table2csv.0.1.1.min.js

(function($)
 {$.fn.table2csv=function(options)
  {
   var defaults=
   {
    delimiter:",",callback:function(csv)
    {
     return csv;
    } 
   };
   var settings=$.extend(defaults,options);
   return this.each(function()
   {
    var name=$(this).find("caption").text();
    var csv="";

    $(this).find("td").each(function()
    {
     csv+="\""+$(this).text().replace(/(\")/gim,"\\\"\\\"")+"\""+",";
     alert(csv);
    })  
   开发者_Go百科 csv=csv.replace(/\,$/gim,"");
    settings.callback(csv,name);
   });

  }
 })(jQuery);


You should rewrite the table2csv script; instead of using $().find('td') to locate <td>s, you could use $('tr').children('td') to make sure you are getting the cells of given row.

Beware that a random <table> on the web might contain <th> <tbody> <tfoot> and other semantic stuff.


after including $('tr').children('td') the o/p we get as

"col1","col2","col3","col3","data in col1","data in col2","data in col3" "col1","col2","col3","col3","data in col1","data in col2","data in col3" "col1","col2","col3","col3","data in col1","data in col2","data in col3"

but the output should be "col1","col2","col3","data in col1","data in col2","data in col3"

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜