一旦我触发了event . preventdefault(),我如何再次恢复默认操作?
当前回答
event.preventDefault(); //or event.returnValue = false;
及其反义词(标准):
event.returnValue = true;
来源: https://developer.mozilla.org/en-US/docs/Web/API/Event/returnValue
其他回答
没有与event.preventDefault()相反的方法来理解为什么在调用event.preventDefault()时首先要研究它做什么。
在底层,preventDefault的功能本质上是调用一个返回false,它会停止任何进一步的执行。如果你熟悉Javascript的老方法,就会发现使用return false来取消表单提交事件和使用return true来取消按钮(在jQuery出现之前)曾经很流行。
正如您可能已经根据上面的简单解释得出的那样:event.preventDefault()的反义词是什么都没有。如果您不阻止该事件,默认情况下浏览器将允许该事件发生。
请看下面的解释:
;(function($, window, document, undefined)) {
$(function() {
// By default deny the submit
var allowSubmit = false;
$("#someform").on("submit", function(event) {
if (!allowSubmit) {
event.preventDefault();
// Your code logic in here (maybe form validation or something)
// Then you set allowSubmit to true so this code is bypassed
allowSubmit = true;
}
});
});
})(jQuery, window, document);
在上面的代码中,你会注意到我们正在检查allowSubmit是否为false。这意味着我们将阻止表单使用事件提交。preventDefault,然后我们会做一些验证逻辑,如果我们满意,设置allowSubmit为true。
这实际上是唯一有效的与event.preventDefault()相反的方法——您也可以尝试删除事件,这基本上可以实现相同的效果。
为了执行异步调用,我不得不在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();
});
});
我建议采用以下模式:
document.getElementById("foo").onsubmit = function(e) {
if (document.getElementById("test").value == "test") {
return true;
} else {
e.preventDefault();
}
}
<form id="foo">
<input id="test"/>
<input type="submit"/>
</form>
...除非我遗漏了什么。
http://jsfiddle.net/DdvcX/
在一个同步流中,你只在需要的时候调用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,可以确保上述流是同步的
你可以在"preventDefault"方法之后使用这个
/ /这里evt。目标返回默认事件(例如:默认url等)
var defaultEvent=evt.target;
//这里我们保存默认事件..
if("true")
{
//activate default event..
location.href(defaultEvent);
}
推荐文章
- 我如何使用Jest模拟JavaScript的“窗口”对象?
- 我如何等待一个承诺完成之前返回一个函数的变量?
- 在JavaScript中根据键值查找和删除数组中的对象
- 使嵌套JavaScript对象平放/不平放的最快方法
- 如何以及为什么'a'['toUpperCase']()在JavaScript工作?
- 有Grunt生成index.html不同的设置
- 文档之间的区别。addEventListener和window。addEventListener?
- 如何检查动态附加的事件监听器是否存在?
- 防止在ASP中缓存。NET MVC中使用属性的特定操作
- 如何写setTimeout与参数Coffeescript
- 将JavaScript字符串中的多个空格替换为单个空格
- jQuery: keyPress退格键不火?
- XMLHttpRequest Origin null不允许Access-Control-Allow-Origin for file:/// to file:///(无服务器)
- JavaScript: override alert()
- 重置setTimeout