我有一個挑戰,即根據輸入的內容制作表格。
function createTable(){
let table = document.getElementById('table')
let row = document.getElementById('input-row').value
let column = document.getElementById('input-column').value
for(let rowIndex = 0; rowIndex < row; rowIndex ){
let tr = document.createElement('tr')
for(let colIndex = 0; colIndex < column; colIndex ){
let td = document.createElement('td')
tr.appendChild(td)
}
table.appendChild(tr)
document.getElementById('input-row').value = " "
document.getElementById('input-column').value = " "
if(row == " ") {
alert('Number of rows cannot be empty')
return false
}
if(row > 9) {
alert('Number of rows cannot be greater than 9')
return false
}
if(row <= 0) {
alert('Number of rows cannot be less than 1')
return false
}
}
}
<div class="inputs-container">
<div class="inputs-container_rows">
<input type="number" class="inputs" max=9 min=0 id="input-row" maxlength="1">
<h3>Rows</h3>
</div>
<div class="inputs-container_columns">
<input type="number" class="inputs" max=9 min=0 id="input-column">
<h3>Columns</h3>
</div>
</div>
<div class="btn-container">
<button id="btn" onclick="createTable()">Create Table</button>
</div>
<div class="table-container">
<table border="1" id="table">
</table>
</div>
對于驗證,只有 if(row > 9) 正在作業,其他的不作業。
另外,我想在再次按下按鈕時擦除表格,我不知道該怎么做。
uj5u.com熱心網友回復:
我注意到一些問題:
- 由于您將
row值作為 astring,您應該使用該String.length屬性來檢查它是否為空。或者您可以通過與 比較來評估沒有輸入任何值""。 - 您需要
row在比較之前轉換為整數;parseInt()方法可以用于此目的。 - 您應該在回圈之前評估條件。
let table = document.getElementById('table');
let rowElement = document.getElementById('input-row');
let columnElement = document.getElementById('input-column');
function isValid() {
let row = rowElement.value;
if(row.length == 0){
alert('Number of rows cannot be empty');
return false;
}
if(parseInt(row) > 9) {
alert('Number of rows cannot be greater than 9');
return false;
}
if(parseInt(row) <= 0) {
alert('Number of rows cannot be less than 1');
return false;
}
return true;
}
function createTable(){
let row = rowElement.value;
let column = columnElement.value;
if(isValid(row))
{
for(let rowIndex = 0; rowIndex < row; rowIndex )
{
let tr = document.createElement('tr')
for(let colIndex = 0; colIndex < column; colIndex ){
let td = document.createElement('td')
tr.appendChild(td)
}
table.appendChild(tr);
document.getElementById('input-row').value = "";
document.getElementById('input-column').value = "";
}
}
}
<div class="inputs-container">
<div class="inputs-container_rows">
<input type="number" class="inputs" max=9 min=0 id="input-row" maxlength="1">
<h3>Rows</h3>
</div>
<div class="inputs-container_columns">
<input type="number" class="inputs" max=9 min=0 id="input-column">
<h3>Columns</h3>
</div>
</div>
<div class="btn-container">
<button id="btn" onclick="createTable()">Create Table</button>
</div>
<div class="table-container">
<table border="1" id="table"></table>
</div>
uj5u.com熱心網友回復:
如果您有任何需要用戶互動的東西,則需要監聽事件(除非您正在使用prompt(),但這很糟糕)。“click”事件是 goto 事件,但您可以使用更好的事件,特別是如果您使用<form>. 特別是一項活動專門針對以下形式:
submit:當用戶專注于某個欄位并 Enter/Return按下鍵或<button>,<input type="submit">或<input type="image">單擊時,表單將:如果有任何
[required],[pattern],[min],[max], 等屬性或任何驗證方法掛鉤,則驗證自身,從具有
[name]屬性的任何欄位中收集所有值,然后將其發送到服務器,并將回傳回應。
如果它沒有將其發送到的服務器,它將回傳一個空白頁面。下面的示例將在觸發“提交”事件時執行所有操作,但不會將資料發送到服務器。您應該閱讀以下內容:
活動
事件委托
行內事件處理程式是垃圾
表單和表單控制元件(又名欄位)
細節在下面的例子中注釋
/***********
** Creates a given element and appends them.
* @param {String} tag tagName of element to be
* created
* @param {DOM Object} parent DOM object to append to
* @param {Number} times number of times tag is
* created
* @param {String} content string in
* each cell (Default is empty)
* @returns {DOM Object|Array} DOM object or an array of DOM
* objects
*/
const setDOM = (tag, parent, times, content = '') => {
let nodeList = [];
for (let i = 0; i < times; i ) {
let node = document.createElement(tag);
parent.appendChild(node);
node.insertAdjacentHTML('beforeEnd', content);
nodeList.push(node);
}
return times > 1 ? nodeList : times === 1 ? nodeList.pop() : null;
}
/** Event handler passes an Event Object (e) **/
const buildTable = e => {
/** Event Properties/Methods
-Stop normal behavior of form submits
-(io) is all form controls (fieldset, legend, input,
button)
*/
e.preventDefault();
const io = e.currentTarget.elements;
/** Form Data
-(r) number of rows
-(c) number of columns
-(cnt) text if any from #edit
*/
let r = parseInt(io.rows.value);
let c = parseInt(io.cols.value);
let cnt = io.edit.innerHTML;
/** Create the Table
-Clear #box
-Create <table> in #box
-Create <tbody> in table
*/
io.box.replaceChildren();
const table = setDOM('table', io.box, 1);
const tB = setDOM('tbody', table, 1);
/** Create Rows & Columns
-Create all <tr>
-if an array is returned...
...Use .forEach() to create the <td> for each <tr>...
...Otherwise just run setDOM() once to create the <td>
*/
const allRows = setDOM('tr', tB, r);
if (Array.isArray(allRows)) {
allRows.forEach((row, idx) => setDOM('td', allRows[idx], c, cnt));
} else {
setDOM('td', allRows, c, cnt);
}
/** Create tHead
-if #head is checked...
...Create <thead>...
...Create <tr>...
...Create all <th>
*/
if (io.head.checked) {
let tH = table.createTHead();
let hRow = setDOM('tr', tH, 1);
setDOM('th', hRow, c, cnt);
}
/** Create tFoot
-if #foot is checked...
...Create <tfoot>...
...Create <tr>...
...Create all <td>
*/
if (io.foot.checked) {
let tF = table.createTFoot();
let fRow = setDOM('tr', tF, 1);
setDOM('td', fRow, c, cnt);
}
};
// Reference the form and listen for the submit event
const UI = document.forms[0];
UI.onsubmit = buildTable;
*, *::before {box-sizing: border-box;}:root {font: 1ch/1.25 'Segoe UI';}body {font-size: 4ch;}.box {width: 100%;max-width: max-content;background: lightgrey;}.box:empty {border: 0;background: transparent;}.edit {width: 100%;min-width: 50vw;min-height: 50px;overflow-wrap: break-word;word-break: break-word;border: 0;outline: 0;padding: 0;}.group {display: flex;flex-flow: row wrap;justify-content: flex-start;align-items: center;}fieldset, button, input {border-radius: 4px;}input {display: inline-block;font-size: 100%;font-family: Consolas;}label {display: flex;align-items: center;margin-right: 2rem;margin-top: 4px;font-size: 100%;}label b {font-weight: 400;}button {display: block;float: right;width: 80px;margin: 4px 0;font-size: 100%;cursor: pointer;}.num {width: 5ch;}.chx {width: 15px;height: 15px;margin-bottom: -1px;cursor: pointer;}table {table-layout: fixed;border-collapse: collapse;width: 100%;}table, td, th {border: 1px solid #000;}th {background: lime;}tbody td {background: cyan;}tfoot td {background: tomato;}
<main>
<form id='UI'>
<fieldset>
<fieldset class='group'>
<legend>Rows & Columns</legend>
<label>Rows:......<sup>(max. 99)</sup>
<input id='rows' class='num' type='number' min='1' max='99' maxlegnth='3' required></label>
<label>Columns:.<sup>(max. 20)</sup>
<input id='cols' class='num' type='number' min='1' max='20' maxlegnth='3' required></label>
</fieldset>
<fieldset>
<legend>Optional text </legend>
<fieldset id='edit' class='edit' contenteditable></fieldset>
</fieldset>
<fieldset class='group'>
<legend>Optional Sections</legend>
<label><b>Table Head:</b> <input id='head' class='chx' type='checkbox'></label>
<label><b>Table Foot:</b> <input id='foot' class='chx' type='checkbox'></label>
</fieldset>
<button>GO</button>
<fieldset id='box' class='box'></fieldset>
</fieldset>
</form>
</main>
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/425404.html
標籤:javascript 验证
