我在点击方法上的异步 $.post
值的返回值方面遇到问题。
我的网页上有几个句子,我想用 ajax 调用来翻译。我不想让它异步,所以请不要建议它。当页面加载时,会有 4-5 个或更多句子,我希望它“即时”翻译它们。
最后,我找到了一个解决方案,如何使用异步调用的返回值,但我猜,因为它是异步的,这就是为什么我的 e.preventDefault()
没有触发。
从这一点上来说,我不知道如何解决。
$.translate = function (string) {
return $.post(getBaseUrl() + 'ajax.php', {action: 'translate', text: string}, function () {});
};
$('td.operations a.remove').click(function (e) {
var promise = $.translate('Do you really want to hurt me?');
promise.success(function(data){
console.log(e);
if (!confirm(data)) {
e.preventDefault();
}
});
});
e
是一个点击事件,没关系。那么,有人可以帮我吗?
最佳答案
您可以反转逻辑并始终阻止 anchor 点击的默认行为,并在需要时调用 native 点击 DOM 方法,例如:
$('td.operations a.remove').click(function (e) {
e.preventDefault();
var $self = $(this); // keep ref using closure (or you could bind it to promise callback)
var promise = $.translate('Do you really want to hurt me?');
promise.done(function(data){
if (confirm(data)) {
$self.off('click').get(0).click(); // call native click method
}
});
});
仅供引用,延迟对象的 success
方法已弃用,请使用 done
代替。
关于jquery - 对点击事件使用 promise 成功,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37156233/