表识别的ID

时间:2020-03-20 17:13:50

标签: javascript html

我的HTML页面中有几个表:

<body>
    <h1>Array to Table</h1>
 <div class="test">  
    <table id="tableA" name="tableA" border="1" class="table">
        <tr>
            <th>Portugues</th>
            <th>English</th>
        </tr>
    </table>
     <br><br>
     Portugues: <input type="text" name="port" id="port">
     English: <input type="text" name="engl" id="engl"><br><br>
     <button id="btnadd" onclick="btnAddRow()">Add Row</button>
<!-- ---------------------------------------------------------------------- -->   

     <table id="tableB" name="tableB" border="1" class="table">
        <tr>
            <th>test1</th>
            <th>test2</th>
        </tr>
    </table>
</div>      
</body>    

我的Javascript代码:

var x =1;
function btnAddRow()
{
    var portV = document.getElementById('port').value;
    var englV = document.getElementById('engl').value;    

    var table = document.getElementsByTagName('table')[0];

    console.log(table);

    var newRow = table.insertRow(x);

    var cell1 = newRow.insertCell(0);
    var cell2 = newRow.insertCell(1);

    cell1.innerHTML = portV;
    cell2.innerHTML = englV;

    x = x + 1;

}

[0]或[1]将标识第一张或第二张表。

var table = document.getElementsByTagName('table')[0];

没有办法使用其适当的ID来识别它们吗? tableA或tableB?如果是,编码是什么?

1 个答案:

答案 0 :(得分:0)

const tables = document.querySelectorAll('table');

console.log(tables[0].id, tables[1].id, tables[2].id);

// From a loop
tables.forEach((table)=> {
  console.log(table.id);
});

const table1 = document.querySelector('#tableA')
const table2 = document.querySelector('#tableB')
const table3 = document.querySelector('#tableC')

console.log(table1.id, table2.id, table3.id);
 <table id="tableA" name="tableA" border="1" class="table">
   <tr>
     <th>Portugues</th>
     <th>English</th>
   </tr>
 </table>
 
  <table id="tableB" name="tableB" border="1" class="table">
   <tr>
     <th>Portugues</th>
     <th>English</th>
   </tr>
 </table>
 
  <table id="tableC" name="tableC" border="1" class="table">
   <tr>
     <th>Portugues</th>
     <th>English</th>
   </tr>
 </table>