一旦我触发了event . preventdefault(),我如何再次恢复默认操作?
当前回答
这里没有一个解决方案对我有帮助,我这样做是为了解决我的情况。
<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();
}
其他回答
在一个同步流中,你只在需要的时候调用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,可以确保上述流是同步的
我使用了以下代码。这对我来说很有效。
$('a').bind('click', function(e) {
e.stopPropagation();
});
在jQuery中处理一个命令,然后从点击事件继续链接:
例:<a href="http://google.com/" class="myevent">点击我</a>
预防和跟随通过jQuery:
$('a.myevent').click(function(event) {
event.preventDefault();
// Do my commands
if( myEventThingFirst() )
{
// then redirect to original location
window.location = this.href;
}
else
{
alert("Couldn't do my thing first");
}
});
或者简单地运行window。Location = this.href;在preventDefault()之后;
Jquery on()可能是另一个解决方案。特别是涉及到名称空间的使用时。
Jquery on()只是当前绑定事件的方式(而不是bind())。Off()是解除这些绑定。使用名称空间时,可以添加和删除多个不同的事件。
$( selector ).on("submit.my-namespace", function( event ) {
//prevent the event
event.preventDefault();
//cache the selector
var $this = $(this);
if ( my_condition_is_true ) {
//when 'my_condition_is_true' is met, the binding is removed and the event is triggered again.
$this.off("submit.my-namespace").trigger("submit");
}
});
现在,通过使用命名空间,您可以添加多个这样的事件,并能够根据您的需要删除它们。虽然提交可能不是最好的例子,但这可能在点击或按键或其他方面派上用场。
你可以在你的脚本中使用这个附加到一些点击事件:
location.href = this.href;
用法示例如下:
jQuery('a').click(function(e) {
location.href = this.href;
});
推荐文章
- Javascript和regex:分割字符串并保留分隔符
- 如何检查DST(日光节约时间)是否有效,如果是,偏移量?
- 如何打破_。在underscore.js中的每个函数
- 如何在jQuery中获得当前日期?
- 如何创建一个日期对象从字符串在javascript
- 输入触发器按钮单击
- 获取对象的属性名
- 如何检查用户是否可以回到浏览器历史
- 使用jQuery的“.val()”在表单中设置隐藏字段的值不工作
- 相当于字符串。jQuery格式
- jQuery模板引擎
- 如何在vue-cli项目中更改端口号
- Angular 2模板中的标签是什么意思?
- JavaScript .includes()方法的多个条件
- 窗口。亲近与自我。close不关闭Chrome中的窗口