所以我在 html 中有所有这些链接
<a href="#ajax" class="invlink" competition_id="532">Gen Invoice</a>
<a href="#ajax" class="invlink" competition_id="534">Gen Invoice</a>
<a href="#ajax" class="invlink" competition_id="535">Gen Invoice</a>
然后我写了一些绑定(bind)到点击事件的javascript 我希望它提交一个 ajax 请求,并用返回的文本替换 anchor 。 但是,如果我点击了多个链接,以至于其中几个链接异步运行,那么它不会使用返回的文本更新所有 anchor ,只会更新我点击的最后一个 anchor 。
我猜测 anchor 变量每次运行时都会被覆盖,我该如何构建我的代码以便每次触发点击事件时,它都会在完成时更新正确的 anchor ?
这是javascript
<script type="text/javascript">
$(document).ready(function() {
// bind geninvoice function to all invlink's
$('.invlink').bind('click', geninvoice);
});
function geninvoice() {
// stop double clicks
anchor = $(this);
anchor.unbind('click');
competition_id = $(this).attr('competition_id');
$.ajax({
type: "POST",
url: "<?php echo url::site('manage/ajax/geninvoice'); ?>/"+competition_id,
dataType: "json",
beforeSend: function() {
anchor.addClass("loading");
},
success: function(response, textStatus) {
anchor.replaceWith(response.invoice_number);
},
error: function(response) {
alert("Unknown Error Occurred");
anchor.bind('click', geninvoice); // rebind if error occurs
},
complete: function() {
anchor.removeClass("loading");
}
});
}
</script>
最佳答案
是的,问题在于您的 anchor
变量在写入时被“提升”到全局范围。参见 this jsfiddle一个简化的例子。
你可以通过在变量前面放置一个 var
来解决这个问题,这样它的作用域就会被限制在函数中:
function geninvoice() {
// stop double clicks
var anchor = $(this); //<-- put a var here
您可以在这个updated version of the above fiddle 看到修复
请注意,这只会帮助您确定函数内的范围。以下示例中的 x
变量将被提升到全局范围的顶部,即使它已使用 var
声明:
var a = 1;
var b = 1;
if (a === b){
var x = 0;
}
alert(x); //alerts '0'
函数内作用域的优点是我们经常看到以下围绕 jQuery 插件的约定的原因之一:
(function($){
//plugin code
//all variables local to the invoked anonymous function
})(jQuery);
关于javascript - 使用 jquery 更新多个 anchor aysc 时遇到问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5963043/