gpt4 book ai didi

javascript - 如何使用 JavaScript 排列 HTML 表格的列

转载 作者:行者123 更新时间:2023-11-28 09:36:30 26 4
gpt4 key购买 nike

我制作了一个表,可以动态地将行添加到我的 html 表中,它也可以动态地将删除按钮添加到行中。我需要在单击表格标题时排列列!

<body>
<div id="app">
<form id="organiser">
<label id="heading">Organiser</label>
<br/>
<br/>
<label>No:</label>
<input type="text" id="description"/>
<br/>
<label>Importance Level:</label>
<select id="options1">
<option value=" 1 " name="1" id="1"> 1 </option>
<option value=" 2 " name="2" id="2"> 2 </option>
<option value=" 3 " name="3" id="3"> 3 </option>
</select>
<br/>
<label>Due Date:</label>
<input type="date" id="date" />
<br/>
<input type="button" id="add" value="Add" onClick="addRowToTable();"/>
</form>
<br/>
<table border="1" id="table">
<tr>
<th>No</th>
<th>Task</th>
<th>Importance</th>
<th>Date Tasks Due</th>
<th></th>
</tr>
</table>
</div>
</body>

最佳答案

修改了您的代码并进行了大量更改(包括 HTML),请参阅 this fiddle .

我最终得到的 JavaScript 如下

function addRowToTable(table){
var table = document.getElementById('table'),
i = table.rows.length,
tr = table.insertRow(i),
t0 = tr.insertCell(0),
t1 = tr.insertCell(1),
t2 = tr.insertCell(2),
t3 = tr.insertCell(3),
t4 = tr.insertCell(4),
text, elm;

// Give row unique values
tr.setAttribute('name', 'txtRow' + i);
tr.setAttribute('id', 'txtRow' + i);

// First cell
text = document.createTextNode( i );
t0.appendChild( text );

// Second cell
text = document.createTextNode( document.getElementById('description').value || 'N/A' );
t1.appendChild( text );

// Third cell
elm = document.getElementById('options1'); // you need to describe what you're trying to do here better
text = document.createTextNode( elm.value );
t2.appendChild( text );

// Fourth cell
elm = document.getElementById('date');
text = document.createTextNode( elm.value || 'N/A' );
t3.appendChild( text );

// Delete button cell
elm = document.createElement('input');
elm.setAttribute('type', 'button');
elm.setAttribute('value', 'x');
elm.setAttribute('class', 'delete');
elm.onclick = function(e){ deleteButton( tr ); };
t4.appendChild(elm);
}

function sortCol( col ){
var table = document.getElementById('table'),
arr, i;
if( col >= table.rows[0].cells.length) return;

arr = Array.prototype.map.call(table.rows, function( row ){
return [row, row.cells[col].textContent];
});
arr.shift(); // skip ID, Description..

arr.sort( function(a, b){
return a[1].localeCompare( b[1] );
} );

for( i = 0; i<arr.length; i = i + 1){
table.tBodies[0].appendChild( arr[i][0] );
}
}

function deleteButton( tr ){
tr.parentNode.removeChild(tr);
}

关于javascript - 如何使用 JavaScript 排列 HTML 表格的列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12964174/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com