一旦我触发了event . preventdefault(),我如何再次恢复默认操作?
当前回答
这不是对问题的直接回答,但它可能会帮助到一些人。我的观点是,你只根据某些条件调用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
});
其他回答
在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()之后;
function(evt) {evt.preventDefault();}
它的反面
function(evt) {return true;}
干杯!
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");
}
});
现在,通过使用命名空间,您可以添加多个这样的事件,并能够根据您的需要删除它们。虽然提交可能不是最好的例子,但这可能在点击或按键或其他方面派上用场。
我使用了以下代码。这对我来说很有效。
$('a').bind('click', function(e) {
e.stopPropagation();
});
我认为“相反”应该是模拟一个事件。你可以使用.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');
推荐文章
- IE9是否支持console.log,它是一个真实的功能吗?
- Node.js同步执行系统命令
- 如何转义JSON字符串包含换行字符使用JavaScript?
- jQuery等价于JavaScript的addEventListener方法
- jQuery需要避免的陷阱
- JavaScript中变量字符串的XML解析
- 用jQuery切换DIV背景图像
- 'React'指的是一个UMD全局,但当前文件是一个模块
- 为什么useState不触发重新渲染?
- 如何使用回调与useState挂钩在反应
- 网络请求失败
- 如何使用JavaScript大写字符串中每个单词的第一个字母?
- 如何使用箭头函数(公共类字段)作为类方法?
- 使用Javascript的atob解码base64不能正确解码utf-8字符串
- 如何阻止恶意代码欺骗“Origin”报头来利用CORS?