【问题标题】:jQuery beforeSend: $(this).after not working [duplicate]jQuery beforeSend:$(this).after 不工作 [重复]
【发布时间】:2013-06-26 18:39:11
【问题描述】:

我很困惑为什么这段代码不起作用:

HTML:

<li><a id="faktura-generate" rel="regular">Faktúra</a></li>
<li><a id="proforma-generate" rel="proforma">Zálohová faktúra</a></li>

JS:

$('#faktura-generate, #proforma-generate').live('click', function () {
    var type = $(this).attr('rel');
    $.ajax({
        url: 'index.php?route=sale/order/superfaktura&token=<?php echo $token; ?>&order_id=<?php echo $order_id; ?>&type=' + type,
        dataType: 'json',
        beforeSend: function () {
            $(this).after('<img src="view/image/loading.gif" class="loading" style="padding-left: 5px;" />');
        }
    });
}); 

我想在用户单击其中一个链接后显示一个加载图标。 $("#proforma-faktura").after(...) 有效,但 $(this).after(...) 无效。

【问题讨论】:

  • 你忘记了美元符号?
  • 并且 live() 在较新版本的 jQuery 中已被弃用和删除。
  • this 可能是$.ajax,而不是被点击的元素,因为它在另一个函数范围内。
  • 在 AJAX 选项中使用 context: this
  • @Ian - 听起来像是一个答案!不知道context 也可以在beforeSend 处理程序中工作,我确信它只在successerror 中工作,因为我前段时间一直在努力,但是测试它,它似乎确实工作正常。

标签: javascript jquery html


【解决方案1】:

this 不是指您传递给“beforeSend”的匿名函数中的元素。

你可以尝试在闭包中捕获它

$('#faktura-generate, #proforma-generate').live('click', function () {
    var that = this,  //  capture 'this' here
        type = $(this).attr('rel');

    // make a function with access to 'that'
    var myFun = function (data) {
        $(that).after('<img src="view/image/loading.gif" class="loading" style="padding-left: 5px;" />');
    };

    $.ajax({
        url: 'index.php?route=sale/order/superfaktura&token=<?php echo $token; ?>&order_id=<?php echo $order_id; ?>&type=' + type,
        dataType: 'json',
        beforeSend: myFun
    });
});

试试看。

也不再支持直播了,换个方式试试。 (不推荐使用的版本:1.7,已删除:1.9)

【讨论】:

  • 谢谢,现在可以使用了。 OpenCart 仍然使用 jQuery 1.7,但很高兴知道 .live() 已被删除。编辑:我没有创建另一个 myFun 函数,而只是 var that = this ,,, $(that).after() 正在工作。 :)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2013-03-28
  • 2011-12-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-03-23
  • 1970-01-01
相关资源
最近更新 更多