2016-09-13 64 views
1

我已經看到很多關於這個的問題,但是我似乎無法得到它的工作。添加href超鏈接到數據表中的行或字段

我有一個數據表,但我無法得到它的工作。我用引導程序使用python-flask,並使用to_html()將熊貓數據框更改爲html表格。

<table width="100%" class="table table-striped table-bordered table-hover dataTable" id="dataTables-example"><thead> 
<tr style="text-align: right;"> 
    <th>id</th> 
    <th>user</th> 
    <th>status</th> 
</tr> 
</thead> 
<tbody> 
    <tr> 
    <td>1</td> 
    <td>1</td> 
    <td>1</td> 
</tr> 
<tr> 
    <td>2</td> 
    <td>1</td> 
    <td>1</td> 
</tr> 
</tbody> 
</table> 

,並在機身的底部,我有:

<script> 
$(document).ready(function() { 
$('#dataTables-example').DataTable({ 

     "bDestroy": true, 
     "deferRender": true, 
     "columns": [ 
      { "data": "id" }, 
      { 
      "data": "weblink", 
      "render" : function(data, type, row, meta){ 
       if(type === 'display'){ 
        return $('<a>') 
         .attr('href', data) 
         .text(data) 
         .wrap('<div></div>') 
         .parent() 
         .html(); 

       } else { 
        return data; 
       } 
      } 
      } 
     ] 
    }); 
}); 
</script> 

我已經看了很多awnsers的但它們都包含數據作爲JavaScript的JSON,而我的數據已經在html。

+0

我們可以看到原始DataFrame中的數據嗎? – brennan

+0

爲什麼'pandas'標籤? – Kartik

+0

爲什麼'python'標籤? – markpsmith

回答

1

使用columnDefs當你有一個DOM <table>,只需要針對一個或幾列:

$('#dataTables-example').DataTable({ 
    destroy: true, 
    deferRender: true, 
    columnDefs: [{ 
    targets: 0, //<-- index of column that should be rendered as link 
    render : function(data, type, row, meta){ 
     if (type === 'display'){ 
     return $('<a>') 
      .attr('href', data) 
      .text(data) 
      .wrap('<div></div>') 
      .parent() 
      .html(); 
     } else { 
     return data; 
     } 
    } 
    }] 
}) 

它的工作原理在這裏 - >http://jsfiddle.net/j9ez0sbj/

+0

非常感謝jsfiddle示例,否則它會花費我很長時間才能找出dataTables.rowReorder.js是使用此功能的單獨腳本。 – user3605780

+0

我將.text更改爲.text('myurl?id ='+ data);你知道我是如何顯示數據(ID),而不是整個網址? – user3605780

+0

hey @ user3605780 - '.attr('href','myurl?id ='+ data)'並保留'.text(data)'...?這是你想改變的'href'。 – davidkonrad

0

您的html表格中有3列,但只在初始化時定義了2列。

從爲columns initialization option數據表文件:

需要注意的是,如果你使用的列來定義列,您必須在數組中爲您在表中有每列中的條目(這些都可以如果您不想指定任何選項,則返回null)。

根據你的意圖是什麼,至少是你需要添加一個定義爲第三列,所以是這樣的:

"columns": [ 
     { "data": "id" }, 
     { 
     "data": "weblink", 
     "render" : function(data, type, row, meta){ 
      if(type === 'display'){ 
       return $('<a>') 
        .attr('href', data) 
        .text(data) 
        .wrap('<div></div>') 
        .parent() 
        .html(); 

      } else { 
       return data; 
      }    
     } 
     }, 
     { "data": "status" } // Third column definition added 
    ]