一旦我触发了event . preventdefault(),我如何再次恢复默认操作?
当前回答
我建议采用以下模式:
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/
其他回答
这不是对问题的直接回答,但它可能会帮助到一些人。我的观点是,你只根据某些条件调用preventDefault(),因为如果你对所有情况调用preventDefault(),就没有必要有一个事件。因此,只有在条件满足时才使用if条件和调用preventDefault(),才能在其他情况下以通常的方式运行该函数。
$('.btnEdit').click(function(e) {
var status = $(this).closest('tr').find('td').eq(3).html().trim();
var tripId = $(this).attr('tripId');
if (status == 'Completed') {
e.preventDefault();
alert("You can't edit completed reservations");
} else if (tripId != '') {
e.preventDefault();
alert("You can't edit a reservation which is already attached to a trip");
}
//else it will continue as usual
});
在一个同步流中,你只在需要的时候调用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,可以确保上述流是同步的
我认为“相反”应该是模拟一个事件。你可以使用.createEvent()
以下Mozilla的例子:
function simulateClick() {
var evt = document.createEvent("MouseEvents");
evt.initMouseEvent("click", true, true, window,
0, 0, 0, 0, 0, false, false, false, false, 0, null);
var cb = document.getElementById("checkbox");
var cancelled = !cb.dispatchEvent(evt);
if(cancelled) {
// A handler called preventDefault
alert("cancelled");
} else {
// None of the handlers called preventDefault
alert("not cancelled");
}
}
裁判:document.createEvent
jQuery有.trigger(),因此可以触发元素上的事件——有时很有用。
$('#foo').bind('click', function() {
alert($(this).text());
});
$('#foo').trigger('click');
正如@Prescott所评论的,相反的是:
evt.preventDefault();
可能是:
本质上等同于'做违约',因为我们不再阻止它。
否则,我倾向于让你看看其他评论和答案提供的答案:
如何解除调用event.preventDefault()的监听器(使用jQuery)?
如何重新启用event.preventDefault?
请注意,第二个已经接受了一个由redsquare给出的示例解决方案(在这里发布了一个直接解决方案,以防这不是封闭的重复):
$('form').submit( function(ev) {
ev.preventDefault();
//later you decide you want to submit
$(this).unbind('submit').submit()
});
这段代码为我重新实例化事件后,我已经使用:
event.preventDefault(); to disable the event.
event.preventDefault = false;
推荐文章
- 我如何使用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