Javascript jQuery在ajax调用中选择附加元素无效

Javascript jQuery在ajax调用中选择附加元素无效,javascript,jquery,ajax,Javascript,Jquery,Ajax,在代码中,.moneychoose是moneychoose.jsp中的div$无法在ajax调用中选择(“.moneychoose”) $("input[name='money']").on("click", function() { if ($("#money").find(".moneychoose")) { $(".moneychoose").remove(); } //append external html $.get("moneych

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

$("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);
        }
    });
});
但如果我在“附加外部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);
            }
    });
});

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

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


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

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

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


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

您还有其他的
})最后?假设其发布错误
if($(“#money”).find(“.moneychoose”)
将始终为真。如果您想知道选择器是否找到任何内容,请添加
.length>0
。大括号未正确匹配。我想修复代码缩进,但我不能用这样的无效代码来修复它。您还有额外的
})最后?假设其发布错误
if($(“#money”).find(“.moneychoose”)
将始终为真。如果您想知道选择器是否找到任何内容,请添加
.length>0
。大括号未正确匹配。我想修复代码缩进,但我不能用这样无效的代码。