2016-11-15 14 views
1

我使用PapaParse解析CSV中的數據並將結果顯示在HTML表格中。 HTML表格包含一個包含URL的列。目前我的解析器以TEXT格式解析它們。我希望這些網址可以點擊,但它們是文本格式。使單個HTML表格列中的JS可點擊嗎? (CSV解析到HTML表格)

的HTML:

<html> 
    <head> 
     <script src="https://code.jquery.com/jquery-2.1.1.min.js"></script> 
     <script src="http://papaparse.com/resources/js/papaparse.js"></script> 
     <script src="test.js"></script> 
     <link rel="stylesheet" href="main.css"> 
     <meta charset="utf-8"> 
    <meta http-equiv="refresh" content="120"><!-- REFRESH EVERY 2 minutes --> 
     <title>JS Bin</title> 
    </head> 
    <body> 
     <table id="results"> 
      <tbody> 
      </tbody> 
     </table> 

    </body> 
    </html> 

中的JavaScript:

$(function() { 
    Papa.parse("data/file.csv", { 
     download: true, 
     complete: function(results) { 
      console.log("Remote file parsed!", results.data); 
      $.each(results.data, function(i, el) { 
       var row = $("<tr/>"); 
       row.append($("<td/>").text("")); /**List Number**/ 
       $.each(el, function(j, cell) { 
        if (cell !== "") 
         row.append($("<td/>").text(cell)); 
       }); 
       $("#results tbody").append(row); 
      }); 
     } 
    }); 
}); 

FILE.CSV

1, search, www.google.com 
2, car, www.autotrader.com 
3, news, www.bbc.co.uk/news 

輸出的電流會是以上所有字段,但都是文本格式。我希望所有最後的字段(網址)都是可點擊的。這是可能的,使用我的上述方法?

這是不是重複的:How to replace plain URLs with links? - 它與解析CSV文件無關,正則表達式的原則可能過於複雜的這種用例。必須有一個簡單的解決方案

回答

1

您在創建表格行時遇到麻煩。正確的方法是:

  • row.append($(「」,{text:cell})); //如果它不是最後一個單元格或URL
  • row.append($(「」)。append($('',{href:cell,text:cell})));

的片段:

//Papa.parse("data/file.csv", { 
 
Papa.parse('1, search, www.google.com\n\ 
 
2, car, www.autotrader.com\n\ 
 
3, news, www.bbc.co.uk/news\n', { 
 
      //download: true, 
 
      complete: function(results) { 
 
    //console.log("Remote file parsed!", results.data); 
 
    $.each(results.data, function(i, el) { 
 
    var row = $("<tr/>"); 
 
    $.each(el, function(j, cell) { 
 
     if (cell !== "") { 
 
     if (j != 2) { 
 
      row.append($("<td/>", {text: cell})); 
 
     } else { 
 
      row.append($("<td/>").append($('<a/>', {href: cell, text: cell}))); 
 
     } 
 
     } 
 
    }); 
 
    $("#results tbody").append(row); 
 
    }); 
 
} 
 
});
<script src="https://code.jquery.com/jquery-2.1.1.min.js"></script> 
 
<script src="https://cdnjs.cloudflare.com/ajax/libs/PapaParse/4.1.2/papaparse.js"></script> 
 

 
<table id="results"> 
 
    <tbody> 
 
    </tbody> 
 
</table>