Jquery动态初始化

时间:2016-06-01 17:53:17

标签: jquery ajax asp.net-mvc

我有以下部分视图

<tr>
<td>
    <input type="hidden" name="InspectionQuestionAnswers.Index" value="@Model.GenID">
    @Html.Hidden("InspectionQuestionAnswers[" + Model.GenID + "].GenID", Model.GenID, new { id = "InspectionQuestionAnswers_" + Model.GenID + "__InspectionQuestionID" })
    @Html.Hidden("InspectionQuestionAnswers[" + Model.GenID + "].ID", Model.ID, new { id = "InspectionQuestionAnswers_" + Model.GenID + "__InspectionQuestionID", @class = "form-control" })
    @Html.Hidden("InspectionQuestionAnswers[" + Model.GenID + "].InspectionTemplateQuestionID", Model.InspectionTemplateQuestionID, new { id = "InspectionQuestionAnswers_" + Model.GenID + "__InspectionQuestionID", @class = "form-control" })
    @Html.TextBox("InspectionQuestionAnswers[" + Model.GenID + "].Answer", Model.Answer, new { id = "InspectionQuestionAnswers_" + Model.GenID + "__InspectionQuestionID", @class = "form-control" })
</td>
<td question_type="row_default">
    @Html.TextBox("InspectionQuestionAnswers[" + Model.GenID + "].Identifier", Model.Identifier, new { id = "InspectionQuestionAnswers_" + Model.GenID + "__InspectionQuestionID", @class = "form-control" })
</td>
<td question_type="row_default">
    @Html.CheckBox("InspectionQuestionAnswers[" + Model.GenID + "].ForcePhoto", Model.ForcePhoto, new {id = "InspectionQuestionAnswers_" + Model.GenID + "__InspectionQuestionID", @class = "checkbox checkbox-inline"}) Require Proof
</td>
<td question_type="row_stock">
    @Html.TextBox("InspectionQuestionAnswers[" + Model.GenID + "].MinStock", Model.MinStock, new { id = "InspectionQuestionAnswers_" + Model.GenID + "__InspectionQuestionID", @class = "form-control" })
</td>
<td>
    <a class="btn btn-danger pull-right ajax-remove" href="@Url.Action("DeleteAnswer")/@Model.ID">Delete</a>
</td>

使用Ajax将此部分视图添加到表中。但是,即使我已将其放入以下函数ajax-remove

,也未初始化类$(document).ready(function ()

这是Ajax方法

        $(".ajax-remove").on("click", function (e) {
            e.preventDefault();
            var sender = $(this).closest('tr');
            var elementUrl = $(this).attr('href');
            $.ajax({
                url: elementUrl,
                cache: false,
                success: function (data) {
                    sender.remove();
                }
            });
        });

上面的Ajax永远不会发生,它只是简单地重定向到url作为白页。

如果我动态地将html添加到初始化jquery方法/列表器的页面,我该如何确保

1 个答案:

答案 0 :(得分:2)

由于您的html是通过ajax调用动态生成的,因此您需要delegated event

 $(document).on("click",".ajax-remove", function (e) {
            e.preventDefault();
            ............
            ............
        });

您可以使用DOM加载项上最接近的父级来获得更好的性能,而不是document