一旦我触发了event . preventdefault(),我如何再次恢复默认操作?
当前回答
我认为“相反”应该是模拟一个事件。你可以使用.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');
其他回答
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;
});
function(evt) {evt.preventDefault();}
它的反面
function(evt) {return true;}
干杯!
在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中延迟表单提交。下面是简化的代码…
$("$theform").submit(function(e) {
e.preventDefault();
var $this = $(this);
$.ajax('/path/to/script.php',
{
type: "POST",
data: { value: $("#input_control").val() }
}).done(function(response) {
$this.unbind('submit').submit();
});
});
推荐文章
- 如何使用JavaScript代码获得浏览器宽度?
- event.preventDefault()函数在IE中无法工作
- indexOf()和search()的区别是什么?
- 错误:'types'只能在.ts文件中使用- Visual Studio Code使用@ts-check
- React-Native:应用程序未注册错误
- LoDash:从对象属性数组中获取值数组
- src和dist文件夹的作用是什么?
- jQuery UI对话框-缺少关闭图标
- 如何使用AngularJS获取url参数
- 将RGB转换为白色的RGBA
- 如何将“camelCase”转换为“Camel Case”?
- 我们可以在另一个JS文件中调用用一个JavaScript编写的函数吗?
- 如何使用JavaScript重新加载ReCaptcha ?
- jQuery。由于转义了JSON中的单引号,parseJSON抛出“无效JSON”错误
- 在JavaScript关联数组中动态创建键