我有一個在應用程式中構建的表,當我單擊洗掉時,會洗掉提交時洗掉的行之后的所有行。這意味著該表對用戶來說看起來不錯,只洗掉了一行,但是當它在發布操作時點擊視圖模型時,這些后續行不包括在內。
我添加了一些非常復雜的代碼,這些代碼遍布各處以編輯行的索引值,但最終使問題更加混亂,一些值替換了其他值,而其他一些值被設定為 0。我知道有成為一種更簡單的方法。
我將此示例設定回更簡化的版本,其中洗掉似乎運行良好,但當它到達控制器時,視圖模型中不包含任何后續值。
這是 HTML 表
<input type="button" value="Add" class="button is-primary" id="btnAdd" />
<table id="tblPart" style="table-layout:fixed; width:100%;">
<thead>
<tr>
<th>
Part Number
</th>
<th>
Quantity
</th>
<th></th>
</tr>
</thead>
<tbody>
@for (var i = 0; i < Model.NumberModel.Count(); i )
{
<tr >
<td >
@Html.TextBoxFor(modelItem => Model.NumberModel[i].PartNum, new { id = $"part{i}", required = "required", @class = "partTest" })
</td>
<td>
@Html.TextBoxFor(modelItem => Model.NumberModel[i].Quantity, new { type = "number", min = "0", id = $"quantity{i}", required = "required" })
</td>
<td>
<input type='button'
onclick='Remove(this)'
value='Remove' />
</td>
</tr>
}
</tbody>
</table>
這是JS
<script>
function Remove(button) {
//Determine the reference of the Row using the Button.
var row = $(button).closest("TR");
var name = $("TD", row).eq(0).html();
//console.log(row name);
var index = 0;
var table = $("#tblPart")[0];
//Delete the Table row using it's Index.
table.deleteRow(row[0].rowIndex);
}
</script>
謝謝您的幫助。
uj5u.com熱心網友回復:
當你洗掉該行時,所有后續行的索引都是錯誤的,你需要在洗掉時重新索引剩余的行。例如,如果您洗掉索引為 3 的行,然后您有第 0-2 行和第 4-6 行,由于沒有索引 3,4-6 將被忽略,要解決此問題,您需要重新索引 id 和 name 屬性在洗掉后的表單欄位上,您還應該考慮在您的as中使用constand應該用于全域變數,最后,當您在代碼中混合 javascript 和 jquery 時,我在您的帖子中添加了 jquery 標記:letfunctionvar
function Remove(button) {
//Determine the reference of the Row using the Button.
const row = $(button).closest("TR");
const name = $("TD", row).eq(0).html(); //this seems unnecessary
let index = 0; //this seems unnecessary
const table = $("#tblPart")[0];
//Delete the Table row using it's Index.
table.deleteRow(row[0].rowIndex);
//re-index
$('#tblPart tbody tr').each(function(i, el) {
//get the form fields
const $partnuminput = $(el).find('input[name*="PartNum"]');
const $quantityinput = $(el).find('input[name*="Quantity"]');
//use the iterator parameter of .each to set the index correctly
$partnuminput.attr("name", $partnuminput.attr("name).replace(/\d /g, i);
$partnuminput.attr("id", $partnuminput.attr("id").replace(/\d /g, i);
$quantityinput.attr("name", $partnuminput.attr("name).replace(/\d /g, i);
$quantityinput.attr("id", $partnuminput.attr("id").replace(/\d /g, i);
});
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/475755.html
標籤:javascript html jQuery 模型视图控制器
