如何使用 JavaScript 避免向表格中插入 NULL 值?
為了避免將空值插入到表中,您需要在輸入值時檢查條件。
檢查 NULL 的條件如下:
while( !( yourVariableName1==null || yourVariableName2==null || yourVariableName3==null…...N){ // yourStatement1 . . N }
以上邏輯將永遠不允許插入空值。
現在您可以使用 for 迴圈並將值插入到表格中而無需 NULL。以下是程式碼:
示例
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initialscale=1.0"> <title>Document</title> <link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css"> <script src="https://code.jquery.com/jquery-1.12.4.js"></script> <script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/fontawesome/4.7.0/css/font-awesome.min.css"> </head> <body> <h2>Demo Of Inserting the value into the table</h2> <p>This is demo on the javascript array</p> <p id="demo"></p> <script> var index = 0; var firstNameArray = new Array(); var lastNameArray = new Array(); var firstName = ""; var lastName = ""; while (!(firstName == null || lastName == null)) { firstName = prompt("Please Enter your First Name="); lastName = prompt("Please Enter your Last Name="); firstNameArray[index] = firstName; lastNameArray[index] = lastName; index++; } document.writeln("<table border='1' width='50%'>"); document.writeln("<caption>DEMO TABLE IN JAVASCRIPT</caption>"); document.writeln("<th>FirstName</th><th>LastName</th>"); for (var startIndex in firstNameArray) { if (firstNameArray[startIndex] !== null && lastNameArray[startIndex] !== null) document.writeln("<tr><td>" + firstNameArray[startIndex] + "</td><td>" + lastNameArray[startIndex] + "</td></tr>"); } document.write("</table>"); </script> </body> </html>
要執行以上程式,請儲存檔名為“anyName.html(index.html)”,然後右鍵單擊該檔案。在 VS Code 編輯器中選擇“使用即時伺服器開啟”選項。
輸出
這將產生以下輸出:
現在輸入名字。
這將產生以下輸出:
單擊“確定”按鈕後,您將獲得以下輸出:
現在,輸入姓氏這將產生以下輸出:
單擊“確定”按鈕後,現在連續單擊兩次“取消”按鈕,您將獲得最終輸出。
最終輸出表格如下:
廣告