一旦我触发了event . preventdefault(),我如何再次恢复默认操作?
当前回答
在一个同步流中,你只在需要的时候调用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');
这不是对问题的直接回答,但它可能会帮助到一些人。我的观点是,你只根据某些条件调用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
});
我建议采用以下模式:
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/
你可以在你的脚本中使用这个附加到一些点击事件:
location.href = this.href;
用法示例如下:
jQuery('a').click(function(e) {
location.href = this.href;
});
function(evt) {evt.preventDefault();}
它的反面
function(evt) {return true;}
干杯!
推荐文章
- Javascript和regex:分割字符串并保留分隔符
- 如何检查DST(日光节约时间)是否有效,如果是,偏移量?
- 如何打破_。在underscore.js中的每个函数
- 如何在jQuery中获得当前日期?
- 如何创建一个日期对象从字符串在javascript
- 输入触发器按钮单击
- 获取对象的属性名
- 如何检查用户是否可以回到浏览器历史
- 使用jQuery的“.val()”在表单中设置隐藏字段的值不工作
- 相当于字符串。jQuery格式
- jQuery模板引擎
- 如何在vue-cli项目中更改端口号
- Angular 2模板中的标签是什么意思?
- JavaScript .includes()方法的多个条件
- 窗口。亲近与自我。close不关闭Chrome中的窗口