我正在使用 PapaParse 解析 CSV 中的数据并在 HTML 表格中显示结果。 HTML 表包含一个带有 URL 的列。目前我的解析器正在以文本格式解析它们。我希望这些 URL 是可点击的,但它们是文本格式的。
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);
});
}
});
});
文件.csv
1, search, www.google.com
2, car, www.autotrader.com
3, news, www.bbc.co.uk/news
当前输出将是上述所有字段,但均为文本格式。我希望最后的所有字段(URL)都是可点击的。使用我上面的方法这可能吗?
这不重复:How to replace plain URLs with links? - 它与解析 CSV 文件无关,并且正则表达式原则对于这个用例来说可能过于复杂。必须有一个更简单的解决方案
最佳答案
您在创建表行时遇到问题。正确的做法是:
- row.append($("", {text: cell}));//如果不是最后一个单元格或 URL
- row.append($("").append($('', {href: 单元格, 文本: 单元格})));
代码片段:
//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>
关于javascript - 使 URL 在单个 HTML 表列中的 JS 中可点击? (CSV 解析为 HTML 表),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40616552/