Ajax发布完成后触发单击事件

时间:2015-01-12 10:55:46

标签: javascript jquery ajax dom

我试图触发一次点击事件并完成Ajax帖子。但是,它没有触发,因为该元素在DOM中不可用。我在Ajax帖子的.load回调中调用了一个jQuery success方法来加载新的DOM元素。

Ajax帖子:

$.ajax({
    type: "POST",
    url: $formAction,
    data: $form.serialize(),
    success: function (result) {
        if (result.constructor === Array) {
            $categoryValidationPanel.html('');
            $.each(result, function (index, value) {
                $categoryValidationPanel.append("<li>" + result[index].ErrorMessage + "</li>")
            });
        } else {
            $dialog.modal('hide');
            refreshComplaintCategoryResults(); //Call to load method below
        }
    },
    error: function () {
        alert("There was a problem processing your request, please try again.");
    }
}).done(function () {
    $("tr[data-action-url='/Admin/ComplaintWorkflow/Edit?categoryId=" + $categoryId + "']").trigger("click");
});

加载方法:

function refreshComplaintCategoryResults() {
    $(".complaint-category-results").load('ComplaintWorkflow/GetComplaintCategoryResults');
}

我希望执行顺序为:

  1. Ajax post
  2. 成功通过refreshComplaintCategoryResults()
  3. 将新创建的元素加载到DOM中
  4. 执行.done并触发点击 新创建的DOM元素
  5. 但是,情况并非如此,.load方法调用处于挂起状态,直到执行.done之后,因此DOM未更新。

    我也在.load方法中尝试了这个(从ajax帖子传递categoryId):

    function refreshComplaintCategoryResults(categoryId) {
        $(".complaint-category-results").load('ComplaintWorkflow/GetComplaintCategoryResults', function () {
            $("tr[data-action-url='/Admin/ComplaintWorkflow/Edit?categoryId=" + categoryId + "']").trigger("click");
        });
    }
    

    有人能建议我在这里缺少什么吗?

    更新

    我现在在DOM中创建了新创建的元素,然后执行相关的触发器代码,但由于某种原因它不会执行。我将加载方法更新为(感谢@TrueBlueAussie对此的评论):

    function refreshComplaintCategoryResults(categoryId) {
        $.get("ComplaintWorkflow/GetComplaintCategoryResults", function (result) {
            $(".complaint-category-results").html('');
            $(".complaint-category-results").html(result);
        })
        .done(function () {
            $("tr[data-action-url='/Admin/ComplaintWorkflow/Edit?categoryId=" + categoryId + "']").trigger("click");
        });
    }
    

    触发器代码无效。我在控制台中调试过,选择器肯定有效。如果我让代码运行然后在控制台中执行相同的代码,触发器就会起作用。

    有什么想法吗?

1 个答案:

答案 0 :(得分:-1)

使用jquery延迟对象是最好的解决方案。您可以在完成ajax请求后根据需要链接回调。这是一个关于如何使用jquery延迟对象的链接 - http://api.jquery.com/category/deferred-object/