jQuery选择ajax调用中附加的元素不起作用

jQuery select the appended element in an ajax call dose not work

本文关键字:元素 不起作用 选择 ajax 调用 jQuery      更新时间:2023-09-26

在代码中,.moneychoot是moneychoose.jsp中的div。在ajax调用中不能选择$(".moneychove")。

$("input[name='money']").on("click", function() {
    if ($("#money").find(".moneychoose")) {
        $(".moneychoose").remove();
    }
    //append external html
    $.get("moneychoose.jsp", function (data) {
        $("#money").append(data);
    });
    $.ajax({
        type: "POST",
        url: "src/province_price.json",
        data: '',
        dataType: "json",
        async: "false",
        success: function(response) {
            console.log($(".moneychoose"));
        },
        error: function(qXhr, status, error) {
            alert(status + ':' + error + ':' + qXhr.responseText);
        }
    });
});

但如果我在"append-external html"之后添加console.log($(".moneychoot"),在ajax调用中可以选择$(".moneychoot")。为什么?但是,"append-external html"之后的$(".moneychoot")仍然无法选择。

$("input[name='money']").on("click", function() {
    if ($("#money").find(".moneychoose")) {
        $(".moneychoose").remove();
    }
    //append external html
    $.get("moneychoose.jsp", function (data) {
        $("#money").append(data);
    });
    console.log($(".moneychoose"));
    $.ajax({
        type: "POST",
        url: "src/province_price.json",
        data: '',
        dataType: "json",
        async: "false",
        success: function(response) {
            console.log($(".moneychoose"));
        },
        error: function(qXhr, status, error) {
            alert(status + ':' + error + ':' + qXhr.responseText);
            }
    });
});

您的困惑是因为console.log不是同步的。您的错误是因为您在两个AJAX请求之间存在竞争条件。

//append external html
$.get("moneychoose.jsp", function (data) {
  $("#money").append(data);
});

 $.ajax({
        type: "POST",
        url: "src/province_price.json",
        data: '',
        dataType: "json",
        async: "false",
        success: function(response) {
            console.log($(".moneychoose"));
        },
        error: function(qXhr, status, error) {
            alert(status + ':' + error + ':' + qXhr.responseText);
        }
    });

为了确保.moneychoose$.ajax的成功回调中可用,您需要在两个请求都成功后使用Promise来解析,或者您需要等待执行其中一个请求,直到另一个请求完成。