2017-02-16 28 views
0

我想獲得ID(從我不知道它是字符串還是元素)。我的HTML代碼和Javascript是這樣的:從表格輸入中獲取元素ID

var table = document.getElementById('workerTimes'); 
 
var emptyArray = new Array(100); 
 

 
for (var r = 1, n = table.rows.length; r < n; r++) { 
 
    var element = table.rows[r].cells[0].innerHTML; 
 
    emptyArray.push(element.id); 
 

 
    console.log(element); 
 
}
<table class="table" id="workerTimes"> 
 
    <tbody> 
 
    <tr> 
 
     <th></th> 
 
     <th>Osoba</th> 
 
     <th>Rozpoczął pracę punktualnie</th> 
 
     <th>Zakończył pracę punktualnie</th> 
 
    </tr> 
 
    <tr> 
 
     <td><input type="checkbox" id="50"></td> 
 
     <td>Jan</td> 
 
     <td> 
 
     <button type="button" class="button_positive" onclick="tickClick(50, 0, 0)">✓</button> 
 
     <button type="button" class="button_negative" onclick="tickClick(50, 0, 1)">X</button> 
 
     </td> 
 
     <td> 
 
     <button type="button" class="button_positive" onclick="tickClick(50, 1, 0)">✓</button> 
 
     <button type="button" class="button_negative" onclick="tickClick(50, 1, 1)">X</button> 
 
     </td> 
 
    </tr> 
 
    </tbody> 
 
</table>

和控制檯日誌顯示

<輸入類型= 「複選框」 ID = 「50」>

但我無法獲得此元素的ID並推送到數組。這個怎麼做?

+1

element.innerHTML是文本。你想使用element.children或潛在的element.childNodes – JonSG

回答

1

您正在使用element.innerHTML但這只是文本。 您想使用element.children或可能的element.childNodes爲了使用結果來獲得正確的ID。

var table = document.getElementById('workerTimes'); 
 

 
var emptyArray = new Array(100); 
 

 
for (var r = 1, n = table.rows.length; r < n; r++) { 
 
    var element = table.rows[r].cells[0].children[0]; 
 
    emptyArray.push(element.id); 
 

 
    console.log(element); 
 
    console.log(element.id); 
 
}
<table class="table" id="workerTimes"> 
 
    <tbody> 
 
    <tr> 
 
     <th></th> 
 
     <th>Osoba</th> 
 
     <th>Rozpoczął pracę punktualnie</th> 
 
     <th>Zakończył pracę punktualnie</th> 
 
    </tr> 
 
    <tr> 
 
     <td><input type="checkbox" id="50"></td> 
 
     <td>Jan</td> 
 
     <td> 
 
     <button type="button" class="button_positive" onclick="tickClick(50, 0, 0)">✓</button> 
 
     <button type="button" class="button_negative" onclick="tickClick(50, 0, 1)">X</button> 
 
     </td> 
 
     <td> 
 
     <button type="button" class="button_positive" onclick="tickClick(50, 1, 0)">✓</button> 
 
     <button type="button" class="button_negative" onclick="tickClick(50, 1, 1)">X</button> 
 
     </td> 
 
    </tr> 
 
    </tbody> 
 
</table>

1

我打算假定第一列也是第一列。您可以使用 getElementByTagName(「TH」)[0] .innerText來獲取該元素內的值。 您可以用來獲取元素的另一個函數是getElementByClassName()。您可以將參數「*」傳遞給後兩個函數以獲取所有元素,然後使用索引訪問您感興趣的元素。