我有一個for條件生成的行數爲多個,上下有2個圖標。對了選擇行點擊移動到1個升壓和對選定行向下點擊移動到1個降壓使用JavaScript替換行
<html>
<head>
<body>
<form name="myForm">
<table id="mainTable" border="1" width="100%">
<script>
document.write('<tr>')
document.write('<td>')
document.write('row1')
document.write('</td>')
document.write('</tr>')
document.write('<tr>')
document.write('<td>')
document.write('row2')
document.write('</td>')
document.write('</tr>')
document.write('</table>')
document.write('<table>')
document.write('<tr>')
document.write('<td>')
document.write('<input type="button" value=" move UP " onClick="swapRowUp(getRowIndex(this))"</input>')>
document.write('<input type="button" value="move DOWN" onClick="swapRowDown(getRowIndex(this))"</input>')>
document.write('</td>')
document.write('</tr>')
document.write('</table>')
</script>
</table>
</form>
</body>
</head>
</html>
<script>
var mainTable = document.getElementById("mainTable");
function getRowIndex(el)
{
while((el = el.parentNode) && el.nodeName.toLowerCase() !== 'tr');
if(el)
alert(el.rowIndex);
return el.rowIndex;
}
function swapRowUp(chosenRow) {
if (chosenRow.rowIndex != 0) {
moveRow(chosenRow, chosenRow.rowIndex-1);
}
}
function swapRowDown(chosenRow) {
if (chosenRow.rowIndex != mainTable.rows.length-1) {
moveRow(chosenRow, chosenRow.rowIndex+1);
}
}
function moveRow(targetRow, newIndex) {
if (newIndex > targetRow.rowIndex) {
newIndex++;
}
var mainTable = document.getElementById('mainTable');
var theCopiedRow = mainTable.insertRow(newIndex);
for (var i=0; i<targetRow.cells.length; i++) {
var oldCell = targetRow.cells[i];
var newCell = document.createElement("TD");
newCell.innerHTML = oldCell.innerHTML;
theCopiedRow.appendChild(newCell);
copyChildNodeValues(targetRow.cells[i], newCell);
}
//delete the old row
mainTable.deleteRow(targetRow.rowIndex);
}
function copyChildNodeValues(sourceNode, targetNode) {
for (var i=0; i < sourceNode.childNodes.length; i++) {
try{
targetNode.childNodes[i].value = sourceNode.childNodes[i].value;
}
catch(e){
}
}
}
</script>
我無法進行交換操作,我得到cellIndex爲空
那麼,什麼是問題? – 2012-01-14 11:48:55
刪除你的問題後,它downvoted(http://stackoverflow.com/questions/8861893/swapping-rows-using-a-javascript)和問相同的問題真的不是要走的路。正如我之前說過的,**向我們展示你到目前爲止嘗試過的方法** - *「請爲我寫下我所有的代碼」*問題往往會在這裏皺起眉頭=) – Rob 2012-01-14 15:02:06
我已經發布了我試用過的示例,你能幫我嗎, – nithin 2012-01-14 17:32:09