[英]How to move cell data values from one column to another in HTML table with Javascript?
[英]Javascript: in an HTML table, how to select part of text (matching some regex) from one column, and move it to the next one?
我有一个HTML表,例如2列
第一个中的数据是这样的:(第二个为空-我将_用作“空”-)
1 (5%) | _
2 (10%) | _
3 (15%) | _
供参考的是:
<table id="my_table" >
<tbody>
<tr>
<td>1 (5%)</td>
<td></td>
</tr>
<tr>
<td>2 (10%)</td>
<td></td>
</tr>
<tr>
<td>3 (15%)</td>
<td></td>
</tr>
</tbody>
</table>
我想要该列的每个单元格(在javascript -greasemonkey-中),
移动括号内的数字(=与正则表达式匹配),
到它旁边的单元格,即第二列。
因此表将被转换为
1 | 5%
2 | 10%
3 | 15%
这是:
<table id="my_table" >
<tbody>
<tr>
<td>1</td>
<td>5%</td>
</tr>
<tr>
<td>2</td>
<td>10%</td>
</tr>
<tr>
<td>3</td>
<td>15%</td>
</tr>
</tbody>
</table>
如何做到这一点?
这里有一些简单的函数可以迭代表的行并执行所需的操作。 modTable函数假定传递了一个id,但它可能是对该表的引用。
function modTable(id) {
var table = document.getElementById(id);
var row, rows = table.rows;
var cell, cells, text, t0, t1;
for (var i=0, iLen=rows.length; i<iLen; i++) {
row = rows[i];
text = getText(row.cells[0]);
// Get just leading digits
t0 = text.replace(/\D+.*/,'');
// Get just the part in brackets
t1 = text.replace(/(^.+\()|(\).*$)/g,'');
// Set new values
setText(row.cells[0], t0);
setText(row.cells[1], t1);
}
}
// Simple helpers for modern and older browsers
// Get textContent of an element
function getText(el) {
return el.textContent || el.innerText || '';
}
// Set the textContent of an element
function setText(el, text) {
if (typeof el.textContent == 'string') {
el.textContent = text;
} else if (typeof el.innerText == 'string') {
el.innerText = text;
}
}
可以通过按钮调用它:
<button onclick="modTable('my_table');">Modify the table</button>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.