[英]javascript: Get the value of a cell - Fix table cell value being undefined
[英]Get the value of a table cell in javascript with external script
我有一個簡單的表,里面充滿了MySQL數據庫中的行,HTML部分看起來像這樣
<tbody>
<?php while($row = mysqli_fetch_row($result)){ ?>
<tr class="rows" id="<?php echo $row[0]; ?>"> // the id is an auto incremented int
<td id="col1"><?php echo $row[1]; ?></td>
<td id="col2"><?php echo $row[2]; ?></td>
<td id="col3"><?php echo $row[3]; ?></td>
<td id="col4"><?php echo $row[4]; ?></td>
<td id="col5"><?php echo $row[5]; ?></td>
</tr>
<?php } ?>
</tbody>
它完成了工作,我有一張漂亮的桌子。 現在,我希望如果單擊一行,我將獲得五個具有單元格值的變量。
阻止我的問題是獲取<td>
元素。 這是我在外部javascript文件中嘗試過的方法:
var rows = document.getElementsByClassName('rows');
for (var i=0; i<rows.length; i++){
rows[i].onclick = function(){
console.log(this.getElementById('col1')); // I tried to print it first
}
}
控制台對此進行了響應: Uncaught TypeError: undefined is not a function
。
然后我嘗試了console.log(rows[i].getElementById(vonalkod));
,但它響應Uncaught TypeError: Cannot read property 'getElementById' of undefined
如果我只寫console.log(this);
然后在html中打印出我期望的整個行。
所以我的問題是,通過ID獲取那些單元格的語法是什么?
您可以獲取單元格內容的方法是
document.getElementById('col1').innerHTML
話雖如此,它只有在您擁有一個col1
時才有效:如果您有多個<tr>
之一,則每個都會有五個td
如<td id=col1>
,其余的id相同-s。 那是無效的HTML。 考慮用類或其他PHP替換這些id。
或者,更好的是,您可以完全放棄所有這些笨拙的id
-s並使用類似以下內容的東西:
rows[i].onclick = function() {
console.log(this.childNodes[0].innerHTML); // col1
console.log(this.childNodes[1].innerHTML); // col2
// ... etc
}
它不起作用,因為它是HTMLTableRowElement對象(請參見http://www.w3.org/2003/01/dom2-javadoc/org/w3c/dom/html2/HTMLTableRowElement.html )
在這里,像jQuery這樣的庫非常方便。 使用jQuery編寫的腳本非常簡單
jQuery('.rows').click(function(){
alert(jQuery(this).children('#col1').text());
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.