一旦我触发了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/
其他回答
正如@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()
});
你可以在"preventDefault"方法之后使用这个
/ /这里evt。目标返回默认事件(例如:默认url等)
var defaultEvent=evt.target;
//这里我们保存默认事件..
if("true")
{
//activate default event..
location.href(defaultEvent);
}
这里没有一个解决方案对我有帮助,我这样做是为了解决我的情况。
<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();
}
我建议采用以下模式:
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,可以确保上述流是同步的