我正尝试在浏览器将用户重定向到http://example.com
点击之前执行异步操作。
因此,在ajax调用之后,我再次单击currentTarget进行重定向,但是它不起作用。
<a class="notic_click" href="http://example.com">Button</a>
<a class="notic_click" href="http://example.com">Button</a>
$(".notic_click").on("click", function(e, options) {
options = options || {};
// if it hasn't been clicked already
// run this
if( !options.hasClicked ) {
e.preventDefault();
const self = this;
// some other code
$.get("http://example.com/hello")
.always(function() {
$(self).trigger("click", {hasClicked: true});
});
} else {
// I got here, that means e.preventDefault didn't get called and it should redirect
console.log("should redirect but not redirecting");
}
});
我$(self).off()
在扳机之前尝试过,但无济于事。
我已经尝试过了:
window.location.assign(e.target.href);
这可行。但是我很好奇是什么原因导致上述方法不起作用。
浏览器:Mozilla Firefox(78.0.2)
您的代码看起来做工精细的隔离。话虽这么说,一种更好的方法是始终调用preventDefault()
来停止页面重定向,然后发出异步AJAX请求。该请求完成后,您可以window.location.assign()
用来重定向用户。
$(".notic_click").on("click", e => {
e.preventDefault();
// I'd suggest putting a loading spinner in the UI here to make it clear
// to the user that their request is in process.
$.get("http://example.com/hello").always(() => {
window.location.assign(e.target.href);
});
});
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句