0

我参考了Steven Sanderson 的博客,并尝试在链接的点击事件上实现动态插入控件。现在就我而言,它不起作用。我不知道它有什么问题。删除 Div(包括控件)工作正常。但附加控件不起作用。当我点击“添加更多”链接时,它会在新页面上打开。不在同一页面上呈现添加控件。

我的主视图代码:

<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>
4

2 回答 2

1

live() 已被弃用并在 jQuery 1.9 中被删除

利用on

  $('#editorRows').on("click", "a.deleteInsertRow",function () {
    $(this).parents("div.editorRow:first").remove();
    return false;
});

如果您想了解有关活动的更多信息

于 2013-03-12T08:11:33.890 回答
0

我解决了。其实我把 $("#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>
于 2013-03-12T09:30:04.573 回答