匿名函数变量作用域[js、ajax]
$(".delete").click(
function() {
var thesender = this;
$(thesender).text("Del...");
$.getJSON("ajax.php", {},
function(data) {
if (data["result"])
$(thesender).remove(); // variable defined outside
else
alert('Error!');
}
);
return false;
}
);
如果用户在调用 ajax 回调之前单击另一个“.delete”,这可能会导致问题吗?
$(".delete").click(
function() {
var thesender = this;
$(thesender).text("Del...");
$.getJSON("ajax.php", {},
function(data) {
if (data["result"])
$(thesender).remove(); // variable defined outside
else
alert('Error!');
}
);
return false;
}
);
This can cause problems if user clicks on another ".delete" before the ajax callback is called?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
它会同时触发另一个 ajax 请求,做同样的事情。这是否会导致问题取决于服务器端。
通常,您会删除某种 id 或键...我假设在此代码的后面部分您会这样做,但现在它只是发出另一个删除并调用
ajax.php
...什么结果完全取决于 PHP 页面。当那个 ajax 请求完成时,回调会发生在那个 ajax 请求上,每个请求在这方面都是独立的,因此每个回调都是单独处理的。
thesender
位于当前闭包内,因此对于每个请求及其各自的回调来说它也是唯一的。It will fire another ajax request at the same time doing the same thing. Whether that causes problems or not depends on the server side of things.
Typically you're deleting an id or key of some sort...I assume later in this code you will be, but for now it just issues another delete and call to
ajax.php
...what the result of this is entirely depends on that PHP page.The callback happens for that ajax request when that ajax request finishes, each request in independent in this respect, so each callback is individually handled.
thesender
is inside your current closure, so it's unique as well for each request and it's respective callback.每次调用
click
处理程序时,都会创建一个单独的闭包,因此每个 AJAX 回调都会有一个对正确变量的引用。因此,您无需担心。 (假设服务器可以处理请求)
Each time the
click
handler is called, a separate closure will be created, so each the AJAX callback will have a reference to the correct variable.Therefore, you don't need to worry about it. (Assuming that the server can handle the requests)
它将触发另一个事件。如果您希望事件只触发一次,您可以使用 one 而不是 click 。或者,您可以跟踪 AJAX 请求是否正在进行;例如,通过使用 data 如下:
您还可以通过使用全局变量、添加类来实现相同的目的, ETC。
It will fire another event. You could use one rather than click if you want the event to only fire once. Alternately, you can keep track as to whether an AJAX request is in progress; e.g by using data as follows:
You could also achieve the same thing by using a global variable, adding classes, etc.