我正在尝试将使用 jQuery 创建的元素加载到表中。问题是,这个动态创建的元素需要插入到另一个元素( )之后<th>
,这样表格才能保持漂亮的设计。使用 .after() 时,我的元素被插入到表格中,表格设计看起来不错,但我使用的数据出现的顺序与使用 .before() 插入时相反。为什么我看到 .before() / .after() 的行为相反?
编辑: .before() 为我提供了正确的利率插入顺序,但它在 . 之前插入元素,因此表 cols/rows 不对齐。.After() 为我提供了相反的利率插入,但在此之后添加了元素,因此表保留其行/列。
这是我的代码,因为我的解释可能不是很清楚:
<form id="form">
<label for="interestInput" id="interestRateLabel">Enter interest rate</label>
<input id="interestInput" name="interestRate" type="text">
<a href="#" id="addInput">Add another interest rate</a><br /><br />
<label for="loanAmtInput" id="loanAmtLabel">Enter loan amount</label>
<input id="loanAmtInput" name="loanAmt" type="text">
<button onclick="doCalculation(); return false;">Calculate!</button>
</form>
<div id="standard">
<h1>Standard Repayment</h1>
<table width="600px;" border="1" cellspacing="0" cellpadding="0">
<th scope="col"> </th>
<tr id="totalMonths">
<th scope="row">Total months</th>
</tr>
<tr id="paymentPerMonth">
<th scope="row">Payment/mo</th>
</tr>
<tr id="totalPayment">
<th scope="row">Total payment</th>
</tr>
</table>
</div>
<div id="extended">
<h1>Extended Repayment</h1>
<table width="600px;" border="1" cellspacing="0" cellpadding="0">
<th scope="col"> </th>
<tr id="totalMonths">
<th scope="row">Total months</th>
</tr>
<tr id="paymentPerMonth">
<th scope="row">Payment/mo</th>
</tr>
<tr id="totalPayment">
<th scope="row">Total payment</th>
</tr>
</table>
</div>
<div id="graduated">
<h1>Graduated Repayment</h1>
<table width="600px;" border="1" cellspacing="0" cellpadding="0">
<th scope="col"> </th>
<tr id="totalMonths">
<th scope="row">Total months</th>
</tr>
<tr id="paymentPerMonth">
<th scope="row">Payment/mo</th>
</tr>
<tr id="totalPayment">
<th scope="row">Total payment</th>
</tr>
</table>
</div>
而且,这是相关的JS:
var doCalculation = function() {
$("div#standard table tbody th.rates, div#standard table tbody tr#totalMonths td, div#standard table tbody tr#paymentPerMonth td").remove();
var loanAmount = document.getElementById("loanAmtInput");
$("input[name=interestRate]").each(function(i){
var num = parseInt( $(this).val(), 10 );
var totalMonths = num * 3;
var paymentPerMonth = num + (1/2);
var totalPaymet = num * 120;
console.log(i + "=" + num);
$("div#standard table tbody th[scope=col]").before("<th class=rates>" + num + "% interest rate</th>");
$("div#standard table tbody tr#totalMonths").append("<td>" + totalMonths + "</td>");
$("div#standard table tbody tr#paymentPerMonth").append("<td>" + paymentPerMonth + "</td>");
});
};