[英]How to perform operations on selected rows in checkbox in a table in HTML
我有一個表,我想對用戶檢查過的行執行一些操作(假設在警報中輸出選定的行)。 以下是我失敗的方法 -
<html> <head> <title>Introduction</title> <script> function kro(){ var x = document.getElementsByName('checks'); for (var i = 0;i < x.length;i++){ if(x[i].checked == 1) var selecteddata+=x[i].value+"\\n"; } alert(selecteddata) } </script> </head> <body> <table> <thead> <tr> <th>UserName</th> <th>Post</th> <th>Comments</th> <th>Select</th> </tr> </thead> <tbody> <tr> <td>Ram</td> <td>Sahi hai</td> <td>Ravan:No</td> <td><input type = "checkbox" name = "checks" id='one'/> </td> </tr> <tr> <td>Ravan</td> <td>Kidnap done</td> <td>Ram:I'll kill you</td> <td><input type = "checkbox" name = "checks" id='two'/> </td> </tbody> <p id = "check" ></p> <button onclick="kro()"> Result </button> </body> </html>
我想對選定的行執行進一步的操作,在代碼中,我只想使用警報輸出選定的行。 怎么做?
預期產出-
如果第一行被選中然后
Ram Sahi hai Ravan:No
var selecteddata+=x[i].value+"\\n";
line 會拋出一個錯誤,所以在 for 循環之外聲明變量。 你也需要設置一個值復選框否則會如此on
要從所有td
獲取內容,請獲取復選框的父級並獲取closest
tr
。 然后從每個 td 中獲取text
並將其添加到if
塊的局部變量中
function kro() { var x = document.getElementsByName('checks'); var selecteddata = ''; for (var i = 0; i < x.length; i++) { if (x[i].checked) { let _tt = ''; x[i].closest('tr').querySelectorAll('td').forEach(function(item) { _tt += item.textContent.trim(); }) selecteddata += _tt + "\\n"; } } alert(selecteddata) }
<table> <thead> <tr> <th>UserName</th> <th>Post</th> <th>Comments</th> <th>Select</th> </tr> </thead> <tbody> <tr> <td>Ram</td> <td>Sahi hai</td> <td>Ravan:No</td> <td><input type="checkbox" name="checks" id='one' value='test1' /> </td> </tr> <tr> <td>Ravan</td> <td>Kidnap done</td> <td>Ram:I'll kill you</td> <td><input type="checkbox" name="checks" id='two' value='test2' /> </td> </tbody> <p id="check"></p> <button onclick="kro()"> Result </button>
您定義並連接到變量錯誤。
應該
var foo = ''; // declare outside of loop for (var i=0; i<5; i++) { foo += i + '\\n' // concat to string } console.log(foo) //display it
人們會做的其他方式是使用數組並在最后加入它
var foo = []; // declare outside of loop for (var i=0; i<5; i++) { foo.push(i) // add to array } console.log(foo.join('\\n')) //display it by joining the array items
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.