javascript-用jquery更新多个锚aysc时遇到麻烦

所以我像这样在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>

然后我写了一些JavaScript绑定到click事件
我希望它提交一个ajax请求,并用返回的文本替换锚.
但是,如果我单击了多个链接,从而使多个链接不同步运行,则它不会使用返回的文本更新所有锚点,而只会更新我单击的最后一个锚点.

我猜想每次运行锚参数都会被覆盖,我将如何构造我的代码,以便每次触发click事件时,它会在完成时更新正确的锚?

这是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>

解决方法:

是的,问题在于您编写的锚变量已“提升”到全局范围.简化示例请参见this jsfiddle.

您可以通过在变量前面放置一个var来解决此问题,因此将其范围限制为该函数

function geninvoice() {

    // stop double clicks
    var anchor = $(this); //<-- put a var here

您可以在此updated version of the above fiddle看到修复

注意,这只会帮助您在函数内进行作用域设置.即使使用var声明了以下示例中的x变量,它也会被提升到全局范围的顶部:

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

相关文章

IE6是一个非常老旧的网页浏览器,虽然现在很少人再使用它,但...
PHP中的count()函数是用来计算数组或容器中元素的个数。这个...
使用 AJAX(Asynchronous JavaScript and XML)技术可以在不...
Ajax(Asynchronous JavaScript and XML)是一种用于改进网页...
本文将介绍如何通过AJAX下载Excel文件流。通过AJAX,我们可以...
Ajax是一种用于客户端和服务器之间的异步通信技术。通过Ajax...