我试图用表上表示的ajax更新记录列表,其中每个记录都作为javascript删除链接。如果我预加载该表,则RemoveLink可以正常工作,但是一旦通过ajax更新了div“ RecordListPartialView”,它将不再起作用。
我用萤火虫检查了生成的html代码对于每一行都是正确的。看来浏览器不知道新代码,因此不会触发javascript链接。
有人可以解释一下发生了什么吗?
(1)这是查看代码:
$(".RemoveLink").click(function () {
var _id = $(this).attr("data-id");
var recordToDelete = { id: _id };
var json = $.toJSON(recordToDelete);
$.ajax({
url: '/MortagePayment/RemoveMortageRecord',
type: 'POST',
dataType: 'json',
data: json,
contentType: 'application/json; charset=utf-8',
success: function (data) {
$("#RecordListPartialView").empty();
$("#RecordListPartialView").html(data.Message);
}
});
});
$(".AddLink").click(function () {
var _year = $("#NewRecord_year").val();
var _month = $("#NewRecord_month").val();
var _mortageValue = $("#NewRecord_mortageValue").val();
var newRecord = { year: _year, month: _month, mortageValue: _mortageValue };
var json = $.toJSON(newRecord);
$.ajax({
url: '/MortagePayment/AddMortageRecord',
type: 'POST',
dataType: 'json',
data: json,
contentType: 'application/json; charset=utf-8',
success: function (data) {
$("#RecordListPartialView").empty();
$("#RecordListPartialView").html(data.Message);
$("#NewRecord_year").val(0);
$("#NewRecord_month").val(0);
$("#NewRecord_mortageValue").val(0);
}
});
});
<div id="RecordListPartialView">
@Html.Partial("MortageRecordList", Model.MortageRecordList)
</div>
(2)局部视图
<table id="mortageRecordListTable">
<tr>
<th colspan=4>Current reductions</th>
</tr>
<tr>
<th>Year</th>
<th>Month</th>
<th>Value</th>
<th></th>
</tr>
@foreach (var item in Model) {
<tr id="[email protected]">
<td>
@item.year
</td>
<td>
@item.month
</td>
<td>
@item.mortageValue
</td>
<td>
<p class="RemoveLink" data-id="@item.mortageRecordId">Remove</p>
</td>
</tr>
}
</table>
(3)和控制器:
[HttpPost]
public ActionResult AddMortageRecord(MortageRecord newRecord) {
var mortageRecordSet = MortageRecordSet.GetMortageSet(this.HttpContext);
if (ModelState.IsValid)
mortageRecordSet.AddMortageRecord(newRecord);
string partialViewHtml = RenderPartialViewToString("MortageRecordList", mortageRecordSet.GetMortageItems());
return Json(new { Success = true, Message = partialViewHtml });
}
[HttpPost]
public JsonResult RemoveMortageRecord(int id) {
var mortageRecordSet = MortageRecordSet.GetMortageSet(this.HttpContext);
mortageRecordSet.RemoveMortageRecord(id);
string partialViewHtml = RenderPartialViewToString("MortageRecordList", mortageRecordSet.GetMortageItems());
return Json(new { Sucess = true, Message = partialViewHtml });
}
最佳答案
如果我正确理解您的意思。
如果我预加载表,则RemoveLink可以正常工作,但一旦div
“ RecordListPartialView”通过ajax更新,不再起作用。
用.click
更改您的.live
事件
$(".RemoveLink").live("click",function(){
//any click event code comes here
});