我有两个表,我想在表1的末尾插入表2.使用jQuery这很容易,我想出了一个“好主意”尝试用javascript做。
$(document).ready(function (){
// Version using jQuery
$("#jQuery").on("click",
function () {
$("#lst1").find("tbody").append(
$("#lst2").find("tbody").html()
);
});
// Version using JavaScript
$("#jScript").on("click",
function () {
document.querySelector("#lst1").querySelector("tbody").append(
document.querySelector("#lst2").querySelector("tbody").innerHTML
);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<html>
<body>
<div style="height:70px; overflow:scroll;" tabindex="1">
<table id="lst1" width="100%" border="1" cellspacing="0" cellpadding="0">
<thead>
<tr>
<th colspan="2">Table 1</th>
</tr>
<tr>
<th> code </th>
<th> Name </th>
</tr>
</thead>
<tbody data-role="input-list">
</tbody>
</table>
</div>
<div style="height:70px; overflow:scroll;" tabindex="1">
<table id="lst2" width="100%" border="1" cellspacing="0" cellpadding="0">
<thead>
<tr>
<th colspan="2">Table 2</th>
</tr>
<tr>
<th> code </th>
<th> Name </th>
</tr>
</thead>
<tbody data-role="input-list">
<tr>
<td>00010</td>
<td> </td>
</tr>
<tr>
<td>00020</td>
<td> </td>
</tr>
<tr>
<td>00030</td>
<td> </td>
</tr>
<tr>
<td>00031</td>
<td> </td>
</tr>
<tr>
<td>00040</td>
<td> </td>
</tr>
</tbody>
</table>
</div>
<button id="jQuery">Merge jQuery</button>
<button id="jScript">Merge jScript</button>
</body>
</html>
如何使用append()
jQuery从JavaScript替换append()
?
答案 0 :(得分:1)
在vanilla JavaScript中,它是 .appendChild()
,而不是.append()
而你没有附加.innerHTML
,你必须附加一个DOM节点。
$(document).ready(function (){
// Version using jQuery
$("#jQuery").on("click",
function () {
$("#lst1").find("tbody").append(
$("#lst2").find("tbody").html()
);
});
// Version using JavaScript
$("#jScript").on("click",
function () {
document.querySelector("#lst1").querySelector("tbody").appendChild(
document.querySelector("#lst2").querySelector("tbody")
);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<html>
<body>
<div style="height:70px; overflow:scroll;" tabindex="1">
<table id="lst1" width="100%" border="1" cellspacing="0" cellpadding="0">
<thead>
<tr>
<th colspan="2">Table 1</th>
</tr>
<tr>
<th> code </th>
<th> Name </th>
</tr>
</thead>
<tbody data-role="input-list">
</tbody>
</table>
</div>
<div style="height:70px; overflow:scroll;" tabindex="1">
<table id="lst2" width="100%" border="1" cellspacing="0" cellpadding="0">
<thead>
<tr>
<th colspan="2">Table 2</th>
</tr>
<tr>
<th> code </th>
<th> Name </th>
</tr>
</thead>
<tbody data-role="input-list">
<tr>
<td>00010</td>
<td> </td>
</tr>
<tr>
<td>00020</td>
<td> </td>
</tr>
<tr>
<td>00030</td>
<td> </td>
</tr>
<tr>
<td>00031</td>
<td> </td>
</tr>
<tr>
<td>00040</td>
<td> </td>
</tr>
</tbody>
</table>
</div>
<button id="jQuery">Merge jQuery</button>
<button id="jScript">Merge jScript</button>
</body>
</html>