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

Wil*_*ill 0 javascript ajax jquery

在代码中,.moneychoose是moneychoose.jsp中的div.$(".moneychoose")无法在ajax调用中选择.

$("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);
        }
    });
});
Run Code Online (Sandbox Code Playgroud)

但是如果我在"附加外部html"之后添加console.log($(".moneychoose")),则可以选择ajax调用中的$(".moneychoose").为什么?但是,"附加外部html"之后的$(".moneychoose")仍然无法选择.

$("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);
            }
    });
});
Run Code Online (Sandbox Code Playgroud)

run*_*red 5

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

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

 $.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);
        }
    });
Run Code Online (Sandbox Code Playgroud)

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