[英]How do I append a new row to the body of a table in HTML using a javascript function that acts on a checkbox click?
我一直在使用以下資源:
而我的 HTML 代碼與 javascript function 如下:
<!doctype html>
<html>
<head>
<h1>Checkbox Test</h1>
</head>
<body>
<table class="tb" id="checky">
<thead>
<tr>
<th>Checkbox 1</th>
<th>Checkbox 2</th>
</tr>
</thead>
<tbody>
<tr>
<td><input type="checkbox" name="Team1_checkbox" id="1" onchange="doalert(this)" /> </td>
<td><input type="checkbox" name="Team2_checkbox" id="2" onchange="doalert(this)" /> </td>
</tr>
</tbody>
</table>
<script>
function doalert(checkboxElem) {
if (checkboxElem.checked) {
var table=document.getElementByID("checky");
var row=table.insertRow(0);
alert("checked");
var cell1 = row.insertCell(0);
var cell2 = row.insertCell(1);
cell1.innerHTML = "NEW CELL1";
cell2.innerHTML = "NEW CELL2";
} else {
alert("notchecked");
}
}
</script>
</body>
</html>
選中時的復選框什么都不做,但取消選中時它會顯示警報,所以我不太確定問題出在哪里。
JavaScript、function中的名稱區分大小寫。 你有錯誤:
var table=document.getElementByID("checky");
應該:
var table=document.getElementById("checky");
更改 function 名稱getElementByID
-> getElementById
。
糾正這個小錯誤,一切都會正常。
您的錯誤是試圖返回。 this
只返回this
將返回輸入元素,這不是你想要得到的,你想要返回的是this.checked
它將返回true
或false
,具體取決於復選框是否被選中
我已經重寫了你發現下面的變化
<!doctype html>
<html>
<head>
<h1>Checkbox Test</h1>
</head>
<body>
<table class="tb" id="checky">
<thead>
<tr>
<th>Checkbox 1</th>
<th>Checkbox 2</th>
</tr>
</thead>
<tbody>
<tr>
<td><input type="checkbox" name="Team1_checkbox" id="1" onchange="doalert(this.checked)" /> </td>
<td><input type="checkbox" name="Team2_checkbox" id="2" onchange="doalert(this.checked)" /> </td>
</tr>
</tbody>
</table>
<script>
function doalert(checkboxElem) {
// console.log(checkboxElem);
if (checkboxElem) {
//correct the getElementByID
var table = document.getElementById("checky");
var row = table.insertRow(0);
alert("checked");
var cell1 = row.insertCell(0);
var cell2 = row.insertCell(1);
cell1.innerHTML = "NEW CELL1";
cell2.innerHTML = "NEW CELL2";
} else {
alert("notchecked");
}
}
</script>
</body>
</html>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.