一旦我触发了event . preventdefault(),我如何再次恢复默认操作?
当前回答
这段代码为我重新实例化事件后,我已经使用:
event.preventDefault(); to disable the event.
event.preventDefault = false;
其他回答
这里有一些有用的东西……
首先,我们将单击链接,运行一些代码,然后执行默认操作。这可以使用event实现。看看吧。在这里,我们将尝试在一个新选项卡上访问谷歌,但在我们需要运行一些代码之前。
<a href="https://www.google.com.br" target="_blank" id="link">Google</a>
<script type="text/javascript">
$(document).ready(function() {
$("#link").click(function(e) {
// Prevent default action
e.preventDefault();
// Here you'll put your code, what you want to execute before default action
alert(123);
// Prevent infinite loop
$(this).unbind('click');
// Execute default action
e.currentTarget.click();
});
});
</script>
我使用了以下代码。这对我来说很有效。
$('a').bind('click', function(e) {
e.stopPropagation();
});
这里没有一个解决方案对我有帮助,我这样做是为了解决我的情况。
<a onclick="return clickEvent(event);" href="/contact-us">
函数clickEvent(),
function clickEvent(event) {
event.preventDefault();
// do your thing here
// remove the onclick event trigger and continue with the event
event.target.parentElement.onclick = null;
event.target.parentElement.click();
}
为了执行异步调用,我不得不在jQuery中延迟表单提交。下面是简化的代码…
$("$theform").submit(function(e) {
e.preventDefault();
var $this = $(this);
$.ajax('/path/to/script.php',
{
type: "POST",
data: { value: $("#input_control").val() }
}).done(function(response) {
$this.unbind('submit').submit();
});
});
在一个同步流中,你只在需要的时候调用e.f preventdefault ():
a_link.addEventListener('click', (e) => {
if( conditionFailed ) {
e.preventDefault();
// return;
}
// continue with default behaviour i.e redirect to href
});
在异步流中,你有很多方法,但最常见的是使用window.location:
a_link.addEventListener('click', (e) => {
e.preventDefault(); // prevent default any way
const self = this;
call_returning_promise()
.then(res => {
if(res) {
window.location.replace( self.href );
}
});
});
通过使用async-await,可以确保上述流是同步的