[英]How to make an editable table in MVC using jquery?
我正在使用“數據庫優先”方法構建我的第一個 MVC 應用程序,一切正常,但是,我堅持使用 jQuery 使 MVC 表可編輯(內聯),當我點擊它時,每一行都有一個鏈接鏈接,場景應該如下:-
1 單擊特定行中的鏈接
2-讓這個特定的行可編輯
問題如下:-
1-當我點擊特定行的鏈接時
2-所有行都可以編輯了!!!
這是 HTML 代碼:-
<table id="my_table">
<tr>
<th>
@Html.DisplayNameFor(model => model.AFECode)
</th>
<th>
@Html.DisplayNameFor(model => model.Remarks)
</th>
<th></th>
</tr>
@foreach (var item in Model)
{
<tr contenteditable="false">
<td contenteditable="false">
@Html.DisplayFor(modelItem => item.AFECode)
</td>
<td contenteditable="false">
@Html.DisplayFor(modelItem => item.Remarks)
</td>
<td contenteditable="false">
<a id="edit_link" href="#" onclick="edit()" >edit</a>
}
</table>
這是包含edit()
函數的 Jquery 代碼:-
function edit() {
$("#my_table td").attr("ContentEditable") == "false" ? $("#my_table td").attr("ContentEditable", "true") : $("#my_table td").attr("ContentEditable", "false")
}
現在,我怎樣才能只得到我點擊的鏈接的那一行是可編輯的?
提前致謝
您的$("#my_table td")
選擇器選擇所有<td>
元素,因此切換所有表格單元格的contenteditable
狀態。 由於每個<a>
元素中的重復id
屬性,您還會生成無效的 html。
避免使用行為污染您的標記並使用Unobtrusive Javascript ,並使用相對選擇器來獲取與鏈接關聯的<td>
元素
<a class="edit" href="#">edit</a> <!-- use a class name-->
$('.edit').click(function() {
// to get the associated row
var row = $(this).closest('tr');
// or to get the associated cells
var cells = $(this).closest('tr').children('td');
// or just the sibling cells
var siblings = $(this).closest('td').siblings('td');
});
最初沒有理由添加contenteditable
,您可能希望向用戶提供反饋,以便他們知道他們正在編輯哪一行,例如,您的代碼可能是
@foreach (var item in Model)
{
<tr>
<td>@Html.DisplayFor(modelItem => item.AFECode)</td>
<td>@Html.DisplayFor(modelItem => item.Remarks)</td>
<td><a class="edit" href="#">edit</a></td>
</tr>
}
$('.edit').click(function () {
var row = $(this).closest('tr');
row.toggleClass('isediting'); // add a style to highlight the row
var isediting = row.hasClass('isediting');
$(this).parent('td').siblings('td').prop('contenteditable', isediting);
if (isediting) {
$(this).text('update');
} else {
$(this).text('edit');
}
})
但是請注意,這不是編輯模型的方法。 要么為for
循環中的所有元素生成表單控件,要么在表單中使用EditorTemplate
並提交到控制器方法(請參閱此示例)或使用包含集合中一個項目的表單的 jquery 對話框,並在單擊“編輯”時按鈕,將行數據傳輸到表單控件並使用ajax保存數據,如果成功,更新行中的值。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.