我有这个jquery代码片段,如果我取消注释第一个preventDefault()它会正常工作,但我正在尝试调用第二个preventDefault(),但它不起作用。见下文:
$(document).ready(function () {
$('#btnSubmit').click(function (event) {
if ($('#tracking').val() != "") {
// FIRST preventDefault()
//event.preventDefault();
var url = "/ReceivingLog/CheckTrackingNumber?number=" + $('#tracking').val();
$.get(url, null, function (result) {
if (result == "False") {
// SECOND preventDefault()
event.preventDefault();
}
});
}
});
为什么第二个/嵌套的preventDefault不起作用?如何让第二个preventDefault()工作?
答案 0 :(得分:1)
$.get
是异步的 - 当它的响应返回时,外部线程已经完成,并且触发的事件已正常完成。在响应返回后,您必须再次触发事件:
const button = document.querySelector('button');
button.addEventListener('click', clickListener);
let doSubmit = false;
function clickListener(e) {
// If this was triggered by the `$.get`, return immediately, run the event as normal without interruption:
if (doSubmit) {
console.log('redirecting');
return;
}
e.preventDefault();
//$.get(url, ...
setTimeout(() => {
const success = true;
if (success) {
doSubmit = true;
button.click();
}
}, 500);
}

<form>
<button type="submit">click</button>
</form>
&#13;