微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐