问题描述
- 如何用JS获取TR中TD的某个标签的值。然后根据大小,交换TR的位置
-
例如:<tr> <td> <h6 id="id0" name="name" > 123</h6> </td> </tr> <tr> <td> <h6 id="id1" name="name" > 456</h6> </td> </tr>
用JS 实现后,调换位置。
解决方案
<table id="tb"><tr>
<td> <h6 id="id0" name="name"> 123</h6> </td>
</tr>
<tr>
<td> <h6 id="id1" name="name"> 456</h6> </td>
</tr>
<tr>
<td> <h6 id="id2" name="name"> 789</h6> </td>
</tr>
<tr>
<td> <h6 id="id3" name="name"> 100</h6> </td>
</tr>
</table>
<script>
var tb=document.getElementById('tb'),rows = tb.rows, trs = [];
for (i in rows) trs[i] = rows[i];
console.log(trs);
trs.sort(function (a, b) {
//降序,升序是a在前面
return parseInt(b.cells[0].getElementsByTagName('h6')[0].innerHTML.replace(/s/g, ''))
- parseInt(a.cells[0].getElementsByTagName('h6')[0].innerHTML.replace(/s/g, ''))
});
for (i in trs) tb.appendChild(trs[i]);
</script>
解决方案二:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
</head>
<body>
<table border="1">
<tr>
<td id="first">123</td>
</tr>
<tr>
<td id="second">456</td>
</tr>
</table>
<button onclick="change();">change</button>
</body>
<script>
function change(){
//获取第一个td里面的值
var first=document.getElementById("first");
//获取第二个td里面的值
var second=document.getElementById("second");
var temp; //临时变量,用于交换数据
//交换数据
if(parseInt(first.innerHTML)<parseInt(second.innerHTML)){
temp = first.innerHTML;
first.innerHTML=second.innerHTML;
second.innerHTML=temp;
}
}
</script>
</html>
解决方案三:
JS 插入tr、td
时间: 2024-11-08 19:09:28