我有一个隐藏模式的表,该表动态填充从0到10行的任意位置。我需要从该表的前两行获取数据,以显示在页面上的另一个表中。另外,如果隐藏表有两行以上,它将显示一个按钮以显示隐藏表。我的问题是,仅当隐藏表具有2行或更多行时,我的代码才有效。我是javascript新手,不确定如何解决此问题...
function populatetable {
// checks for table cell id in the hidden table
var rowcheck = document.getElementById('cell1')
var rowyes = document.getElementById('thetable').contains(rowcheck);
var showbutton = document.getElementById('thebutton');
// when button is still hidden
if (document.getElementById('thetable').getElementsByTagName('tr').length <=2 && rowyes == true) {
// variables for table data in hidden table's first row
var data1 = document.getElementById('td1').innerHTML;
var data2 = document.getElementById('td2').innerHTML;
// variable for table data in hiddent table's second row
var data3 = document.getElementById('td3').innerHTML;
var data4 = document.getElementById('td4').innerHTML;
// populates visible table from rows in hidden table
document.getElementById('vtd1').innerHTML = data1;
document.getElementById('vtd2').innerHTML = data2;
document.getElementById('vtd3').innerHTML = data3;
document.getElementById('vtd4').innerHTML = data4;
}
if else (document.getElementById('thetable').getElementsByTagName('tr').length > 2 && rowyes == true) {
showbutton.style.display = 'block';
var data1 = document.getElementById('td1').innerHTML;
var data2 = document.getElementById('td2').innerHTML;
var data3 = document.getElementById('td3').innerHTML;
var data4 = document.getElementById('td4').innerHTML;
document.getElementById('vtd1').innerHTML = data1;
document.getElementById('vtd2').innerHTML = data2;
document.getElementById('vtd3').innerHTML = data3;
document.getElementById('vtd4').innerHTML = data4;
}
}
这仅在隐藏表至少具有两行的情况下有效。有什么想法吗?
答案 0 :(得分:0)
考虑这个学校案例=我们通过在行/单元格中引用HTML表的元素来访问它们:
(最好是使用textContent
来阅读其内容,如果只是文本的话)
如果要使用相同的行副本,最好使用cloneNode
方法=> https://developer.mozilla.org/en-US/docs/Web/API/Node/cloneNode
const myTab = document.querySelector('#my-table tbody')
console.log( 'lines .....= ', myTab.rows.length )
console.log( 'columns ...= ', myTab.rows[0].cells.length )
console.log( 'table[1,3] = ', myTab.rows[1].cells[3].textContent, '(value)')
table { border-collapse: collapse; margin: 1em }
td { border: 1px solid grey; width: 2em; height: 1em; }
<table id="my-table">
<tbody>
<tr><td>0.0</td><td>0.1</td><td>0.2</td><td>0.3</td><td>0.4</td></tr>
<tr><td>1.0</td><td>1.1</td><td>1.2</td><td>1.3</td><td>1.4</td></tr>
<tr><td>2.0</td><td>2.1</td><td>2.2</td><td>2.3</td><td>2.4</td></tr>
<tr><td>3.0</td><td>3.1</td><td>3.2</td><td>3.3</td><td>3.4</td></tr>
</tbody>
</table>