使用 .each 从表创建字符串,如何在每行后添加换行符
Creating string from table with .each, how to add a newline after each row?
我正在使用以下javascript从表的选定单元格中获取数据:
var cellIndexMapping = { 0: true, 1: true, 3:true, 4:true, 5:true};
var data = [];
$j("#myTable tr").each(function(rowIndex) {
$j(this).find("td").each(function(cellIndex) {
if (cellIndexMapping[cellIndex])
data.push($j(this).text() );
});
});
var fullCSV = data.join(", ");
console.log (fullCSV);
这使我的所有表元素都位于逗号分隔的数组中。 例如,如果我的表是
<th>| zero | one | two | three | four | five | </th>
---------------------------------------------
<tr>| A | B | C | D | E | F | </tr>
---------------------------------------------
<tr>| G | H | I | J | K | L | </tr>
我回来了 :
A,B,D,E,F,G,H,J,K,L
我需要的是每行之间的换行符"'n"
。 所以我想要的结果看起来像:
A,B,D,E,F,'n G,H,J,K,L 'n
有什么想法吗?
var cellIndexMapping = { 0: true, 1: true, 3:true, 4:true, 5:true},
data = [],
finalData = [];
$j("#myTable tr").each(function(rowIndex) {
data.push([]);
$j(this).find("td").each(function(cellIndex) {
if (cellIndexMapping[cellIndex])
data[rowIndex].push( $j(this).text() );
});
});
$j.each(data, function(i, e) {
finalData.push( e.join(',') );
});
finalData.join("'n");
或者,您可以在每个循环中附加'n
:
var cellIndexMapping = { 0: true, 1: true, 3:true, 4:true, 5:true},
finalData = '';
$j("#myTable tr").each(function(rowIndex) {
var data = [];
$j(this).find("td").each(function(cellIndex) {
if (cellIndexMapping[cellIndex])
data.push( $j(this).text() );
});
finalData += data.join(', ') + "'n";
});
看到这个小提琴:http://jsfiddle.net/kLsW5/
你只需要在外循环的末尾添加它:
var res = "";
$j("#myTable tr").each(function(rowIndex) {
var data = [];
$j(this).find("td").each(function(cellIndex) {
if (cellIndexMapping[cellIndex])
data.push($j(this).text() );
});
res += data.join(", ") + "'n";
});
现在res
保存最终值。
您确定要在第一行中使用尾随逗号吗?你不想要这样的东西吗:
A,B,D,E,F'nG,H,J,K,L'n
以下是使用 .map()
[docs] 的一种方法:
var cellIndexMapping = { 0: true, 1: true, 3:true, 4:true, 5:true};
var fullCSV = $j("#myTable tr").map(function() {
return $j(this).find("td").map(function(cellIndex) {
return cellIndexMapping[cellIndex] ? $j(this).text() : null;
}).get().join(', ');
}).get().join(''n');
相关文章:
- 如何在映射数组中添加换行符
- JQuery:向多个匹配结果添加换行符的最简单方法
- javascript/jQuery:在title中添加换行符——在IE9中有效,但在IE8中无效
- 在JavaScript中的无操作(空)函数中不添加换行符的选项(IntelliJ Web/PHP风暴)
- 将换行符添加到.text内容文本
- 在javascript数组元素之间添加换行符
- D3 垂直条形图为标签文本添加换行符
- 如何在指定字符后添加换行符
- 为图像上绝对定位的文本块添加换行符以创建文本条带
- 从 PHP 向 JavaScript 添加换行符
- 我将如何使用jquery在html文本区域中按回车符时添加换行符
- 添加换行符 JavaScript pdf 表单时的文本字段空白
- Javascript在mailto正文中添加换行符
- 尝试向字符串中的每个找到的模式添加换行符
- 使用 Javascript/jquery 在
标记后添加换行符
- 向D3图形y轴标签添加换行符
- 如何使用Javascript或Ruby在大块文本中智能地添加换行符
- Javascript添加换行符, 不起作用
- 如何使用XTemplate在x次迭代后添加换行符
- 如何将换行符添加到CakePHP脚本块