Ajax请求不适用于动态控制追加
问题描述:
我已经提到Steven Sanderson's blog,并试图实现在链接的点击事件上动态插入控件。现在在我的情况下,它不工作。我不知道它有什么问题。删除Div(包括控件)工作正常。但追加控件无效。当我点击“添加更多”链接时,它会在新页面上打开。不在同一页面上呈现添加控件。Ajax请求不适用于动态控制追加
我的MainView代码:
<div id="Div1">
<% Html.RenderAction("_EditServices", "CRM", new { id = Model.Id });%>
</div>
<div id="editorRows">
<% Html.RenderAction("_EditInsertServices", "CRM"); %>
</div>
<%= Html.ActionLink("+ Add More Service(s)", "EditAdd", null , new { id = "addItem" })%>
我对_EditInsertServices PartiaView:
<div class="editorRow">
<% using (Html.BeginCollectionItem("services"))
{ %>
NOS:<%:Html.DropDownListFor(model=>model.Id,(SelectList)ViewData["crmServiceType"] as SelectList,"---")%>
Comment:<%=Html.TextBoxFor(model => model.Comment, new { size = "20" })%>
<a class="deleteInsertRow">delete</a>
<% } %>
</div>
我的控制器代码:
public ActionResult EditAdd()
{
ViewData["crmServiceType"] = new SelectList(CRMRequestDL.GetCRM_Service_TypeList().ToArray(), "Id", "ServiceName");
return View("_EditInsertServices", new CommentedService());
}
public ActionResult _EditInsertServices()
{
ViewData["crmServiceType"] = new SelectList(CRMRequestDL.GetCRM_Service_TypeList().ToArray(), "Id", "ServiceName");
return PartialView();
}
脚本:
<script type="text/javascript">
$("#addItem").click(function() {
$.ajax({
url: this.href,
cache: false,
success: function (html) { $("#editorRows").append(html); }
});
return false;
});
$("a.deleteInsertRow").live("click", function() {
$(this).parents("div.editorRow:first").remove();
return false;
});
</script>
答
我解决了它的jQuery 1.9
使用on
$('#editorRows').on("click", "a.deleteInsertRow",function() {
$(this).parents("div.editorRow:first").remove();
return false;
});
被删除。其实我把$(“#addItem”)。click(function(){});函数转换为$(document).ready(function(){});功能,它工作正常。因此,无论何时我使用$(“any class/id”),我都应该将该方法放在$(document).ready()函数中。
这里是解决方案:
<script type="text/javascript">
$(document).ready(function() {
$("#addItem").click(function() {
$.ajax({
url: this.href,
cache: false,
success: function (html) { $("#editorRows").append(html); }});
return false;
});
});
</script>
你用什么版本的jQuery? – 2013-03-12 08:52:13
您是否检查了控制台1)您没有错误2)请求的页面是否正确接收? – 2013-03-12 08:53:26
@dystroy,我没有收到任何错误期望“ReferenceError:$未定义”,而我点击添加更多链接。我认为Html.ActionLink可能存在问题。我的jQuery版本是1.9 – Dhwani 2013-03-12 08:55:24