下面的代码将一列表中的值拆分为斜线分隔符的新行 但是我不在多列表上工作 有时我需要拆分第三列的值。
如果应用于第三列,期望的结果将是这样的。
对于分隔符的每次出现,都会创建一个新行。
下表中的值仅作为示例,实际值并不总是1个字符长。
$('#tbl tr').each(function() {
var $this = $(this);
var arr = $this.text().split('/');
var firstTwo = arr.splice(0, 2);
var firstEl = firstTwo.join('/').trim();
arr.unshift(firstEl);
var len = arr.length;
var i;
var $previous = $this;
for (i = 0; i < arr.length; ++i) {
var $tr = $this.clone();
$tr.find("td").text(arr[i]);
$previous.after($tr);
$previous = $tr;
}
$this.remove();
});
&#13;
th {
height: 15px;
min-width: 30px;
border: 1px solid black;
font-size: 12px;
font-family: Courier, monospace;
padding: 2px 5px 2px 5px;
}
td {
height: 15px;
min-width: 30px;
border: 1px solid black;
font-size: 12px;
font-family: Courier, monospace;
padding: 2px 5px 2px 5px;
}
&#13;
<table id="tbl">
<thead>
<tr class="tbl-header">
<th>1</th>
<th>2</th>
<th>3</th>
<th>4</th>
</tr>
</thead>
<tbody>
<tr>
<td>A/B/C</td>
<td>B/C</td>
<td>C</td>
<td></td>
</tr>
<tr>
<td>A/B</td>
<td>B/C</td>
<td></td>
<td>D/E</td>
</tr>
<tr>
<td></td>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td>A/B/C/D</td>
<td></td>
<td>C/D/E</td>
<td>D/E/F</td>
</tr>
<tr>
<td></td>
<td>B/C/D</td>
<td>C/D</td>
<td>D/E/F/G</td>
</tr>
<tr>
<td>A/B/C</td>
<td>B/C/D/E</td>
<td>C/D/E</td>
<td></td>
</tr>
</tbody>
</table>
&#13;
答案 0 :(得分:1)
这可能会有所帮助......
<script>
$( document ).ready(function() {
$('#tbl tr td:nth-child(3)').each(function() {
var $this = $(this);
var arr = $this.text().split('/');
var $previous = $this.parent();
//console.log($previous);
//console.log(arr.length);
if(arr.length >1){
for (i = 0; i < arr.length; ++i) {
var $tr = $previous.clone();
$previous.after($tr);
var yourCell = $previous.find('td:nth-child(3)');
//console.log(yourCell.text());
yourCell.text(arr[i]);
$previous = $tr;
}
$previous.remove();
}
});
});
</script>