[英]Can't access object made by ajax call
I have this ajax request: 我有这个ajax请求:
$.ajax({
type: "POST",
dataType: "json",
data: dataString,
url: "app/changeQuantity",
success: function(data) {
$('#table').append('<tr><td><a id="uid">click</a></td></tr>');
});
as you can see it makes new row in #table. 你可以看到它在#table中创建了新行。 But this new objects made by ajax are not accessible from next functions.
但是,下一个函数无法访问ajax生成的这些新对象。 Result from ajax is not a regullar part of DOM, or what is the reason for this strange behavior?
来自ajax的结果不是DOM的常规部分,或者这种奇怪行为的原因是什么?
$('#uid').on('click', function () {
alert('ok');
});
Use event delegation: 使用事件委托:
$(document).on('click','#uid', function () {
alert('ok');
});
Note that ajax
calls are asynchronous. 请注意,
ajax
调用是异步的。 So whatever you do with the data
you need to do it in a callback within the success
function (that is the callback which is called when the ajax call returns successfully). 因此,无论您对
data
执行什么操作,都需要在success
函数内的回调中执行此操作(即当ajax调用成功返回时调用的回调)。
Is simple and complex at the same time. 既简单又复杂。 Simple to solve but complex if you are getting started with javascript...
如果您开始使用javascript,很容易解决但很复杂...
Your event handler - onclick is being fired and bound to an object that doesnt yet exist. 你的事件处理程序 - onclick被触发并绑定到一个尚不存在的对象。
So when you append the object to the #table, you need to set up your click handler as the object now exists. 因此,当您将对象附加到#table时,您需要设置单击处理程序,因为该对象现在已存在。
So in your success part of the ajax return add the click handler event there. 所以在你成功的ajax返回部分中添加了click handler事件。
success: function(data) {
$('#table').append('<tr><td><a id="uid">click</a></td></tr>');
$('#uid').on('click', function () {
alert('ok');
});
});
Or how about you make it dynamic and create a function to do it for you. 或者你如何让它变得动态并创建一个为你做的功能。
function bindClick(id) {
$('#' + id).click(function() {
//Do stuff here
console.log('I made it here' + id);
});
}
Then: 然后:
success: function(data) {
$('#table').append('<tr><td><a id="uid">click</a></td></tr>');
bindClick(uid);
});
}
This is a super contrived example but you get the idea you just need to make the rest of it dynamic as well. 这是一个超级人为的例子,但你得到的想法是你只需要使其余部分动态化。 for example some name and counter generated id number: id1, id2, id3...
例如一些名称和计数器生成的id号:id1,id2,id3 ......
Try it like this, add this $('#uid').on('click', function () {
into the success 像这样尝试,添加这个
$('#uid').on('click', function () {
成功
$.ajax({
type: "POST",
dataType: "json",
data: dataString,
url: "app/changeQuantity",
success: function(data) {
$('#table').append('<tr><td><a id="uid">click</a></td></tr>');
$('#uid').on('click', function () {
alert('ok');
});
});
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.