jQuery选择ajax调用中附加的元素不起作用
jQuery select the appended element in an ajax call dose not work
在代码中,.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来解析,或者您需要等待执行其中一个请求,直到另一个请求完成。
相关文章:
- iframe中的jQuery查找元素不起作用
- jQuery选择ajax调用中附加的元素不起作用
- 我的ID获取元素不起作用
- 为什么从 Angular 服务中的对象中删除此元素不起作用
- 将onclick事件附加到元素不起作用
- <标题>插入SVG的元素不起作用
- 使用next()的jQuery目标元素不起作用
- HTML输入元素不起作用
- 使用css显示和隐藏元素不起作用
- 焦点到 DOM 元素不起作用
- Jquery 在图像错误上对多个元素不起作用
- 按类名获取元素不起作用
- jQuery - 'addClass' to HTML 元素 - 不起作用,但在 Chrome 中正确显
- 具有 ID AND 类的 jQuery 选择器目标元素不起作用
- Ajax 对 xml 页面的响应以获取标题元素不起作用
- 单击新 DOM 元素不起作用的事件
- Javascript 添加的动态 svg 元素不起作用
- jQuery on handler 对插入的元素不起作用
- 从表单中删除添加的元素不起作用
- 相对于另一个元素的位置元素不起作用