javascript - 使用 jquery 更新多个 anchor aysc 时遇到问题

标签 javascript jquery ajax asynchronous

所以我在 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);

参见this JSFiddle

关于javascript - 使用 jquery 更新多个 anchor aysc 时遇到问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5963043/

相关文章:

jquery - ASP.NET MVC 使用 JQuery 将页面内容加载到 div 中

javascript - 无法获得 express.js 响应

jquery - 这是最先进的 Ajax/jQuery,还是我应该采取不同的做法?

javascript - 如何使用 ajax-jquery 将选定的复选框数据获取到使用 PHP-CodeIgniter 的模态

javascript - 如何在 JavaScript 中引用原始类型?

javascript - 在 Ajax 的帮助下使用 forismatic APi 读取报价

javascript - 如何正确重置对象项

javascript - 为什么在 onBeforeDeactivate 事件处理程序中调用 focus() 时 DIV 会移动?

jquery - blockui 需要 jquery v1.2.3 或更高版本,您正在使用 v.1.11.1

javascript - AJAX 请求 - 还清除占位符文本以及 HTML 输入字段值