在单击方法上,异步$.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是一个单击事件,没关系。有人能帮我吗?
发布于 2016-05-11 07:59:21
您可以随时逆转逻辑并防止默认行为,因为锚单击并在需要时调用本机单击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。
https://stackoverflow.com/questions/37156233
复制相似问题