如何取消绑定正在调用 event.preventDefault() 的侦听器(使用 jQuery)?

发布于 2024-08-06 22:16:13 字数 85 浏览 7 评论 0 原文

jquery切换默认调用preventDefault(),因此默认值不起作用。 您无法单击复选框,无法单击链接等

是否可以恢复默认处理程序?

jquery toggle calls preventDefault() by default, so the defaults don't work.
you can't click a checkbox, you cant click a link etc etc

is it possible to restore the default handler?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(20

So要识趣 2024-08-13 22:16:14

您可以通过执行以下操作恢复默认操作(如果是 HREF follow):

window.location = $(this).attr('href');

You can restore the default action (if it is a HREF follow) by doing this:

window.location = $(this).attr('href');

橘味果▽酱 2024-08-13 22:16:14

如果它是一个链接,则 $(this).unbind("click"); 将重新启用链接点击,并恢复默认行为。

我创建了 一个演示 JS fiddle 来演示其工作原理:

这是 JS 小提琴的代码:

HTML:

<script src="https://code.jquery.com/jquery-1.10.2.js"></script>
<a href="http://jquery.com">Default click action is prevented, only on the third click it would be enabled</a>
<div id="log"></div>

Javascript:

<script>
var counter = 1;
$(document).ready(function(){
$( "a" ).click(function( event ) {
  event.preventDefault();

  $( "<div>" )
    .append( "default " + event.type + " prevented "+counter )
    .appendTo( "#log" );

    if(counter == 2)
    {
        $( "<div>" )
    .append( "now enable click" )
    .appendTo( "#log" );

    $(this).unbind("click");//-----this code unbinds the e.preventDefault() and restores the link clicking behavior
    }
    else
    {
        $( "<div>" )
    .append( "still disabled" )
    .appendTo( "#log" );
    }
    counter++;
});
});
</script>

if it is a link then $(this).unbind("click"); would re-enable the link clicking and the default behavior would be restored.

I have created a demo JS fiddle to demonstrate how this works:

Here is the code of the JS fiddle:

HTML:

<script src="https://code.jquery.com/jquery-1.10.2.js"></script>
<a href="http://jquery.com">Default click action is prevented, only on the third click it would be enabled</a>
<div id="log"></div>

Javascript:

<script>
var counter = 1;
$(document).ready(function(){
$( "a" ).click(function( event ) {
  event.preventDefault();

  $( "<div>" )
    .append( "default " + event.type + " prevented "+counter )
    .appendTo( "#log" );

    if(counter == 2)
    {
        $( "<div>" )
    .append( "now enable click" )
    .appendTo( "#log" );

    $(this).unbind("click");//-----this code unbinds the e.preventDefault() and restores the link clicking behavior
    }
    else
    {
        $( "<div>" )
    .append( "still disabled" )
    .appendTo( "#log" );
    }
    counter++;
});
});
</script>
就此别过 2024-08-13 22:16:14

测试此代码,我认为可以解决您的问题:

event.stopPropagation();

参考

Test this code, I think solve your problem:

event.stopPropagation();

Reference

牛↙奶布丁 2024-08-13 22:16:14

最好的方法是使用命名空间。这是一种安全可靠的方式。这里 .rb 是命名空间,它确保取消绑定功能适用于特定的按键,但不适用于其他按键。

$(document).bind('keydown.rb','Ctrl+r',function(e){
            e.stopImmediatePropagation();
            return false;
        });

$(document).unbind('keydown.rb');

参考1: http://idodev .co.uk/2014/01/safely-binding-to-events-using-namespaces-in-jquery/

ref2:http://jqfundamentals.com/chapter/events

The best way to do this by using namespace. It is a safe and secure way. Here .rb is the namespace which ensures unbind function works on that particular keydown but not on others.

$(document).bind('keydown.rb','Ctrl+r',function(e){
            e.stopImmediatePropagation();
            return false;
        });

$(document).unbind('keydown.rb');

ref1: http://idodev.co.uk/2014/01/safely-binding-to-events-using-namespaces-in-jquery/

ref2: http://jqfundamentals.com/chapter/events

一紙繁鸢 2024-08-13 22:16:14

如果该元素只有一个处理程序,则只需使用 jQuery 取消绑定即可。

$("#element").unbind();

If the element only has one handler, then simply use jQuery unbind.

$("#element").unbind();
ζ澈沫 2024-08-13 22:16:14

禁用:

document.ontouchstart = function(e){ e.preventDefault(); }

启用:

document.ontouchstart = function(e){ return true; }

Disable:

document.ontouchstart = function(e){ e.preventDefault(); }

Enable:

document.ontouchstart = function(e){ return true; }
卷耳 2024-08-13 22:16:14

Event 接口的 PreventDefault() 方法告诉用户代理,如果事件没有得到显式处理,则不应像通常那样采取其默认操作。事件继续像往常一样传播,除非其事件侦听器之一调用 stopPropagation() 或 stopImmediatePropagation(),这两者都会立即终止传播。

在事件流的任何阶段调用 PreventDefault() 都会取消该事件,这意味着实现通常因该事件而采取的任何默认操作都不会发生。

您可以使用 Event.cancelable 来检查事件是否可以取消。对不可取消的事件调用 PreventDefault() 没有任何效果。

window.onKeydown = event => {
    /*
        if the control button is pressed, the event.ctrKey 
        will be the value  [true]
    */

    if (event.ctrKey && event.keyCode == 83) {
        event.preventDefault();
        // you function in here.
    }
}

The Event interface's preventDefault() method tells the user agent that if the event does not get explicitly handled, its default action should not be taken as it normally would be. The event continues to propagate as usual, unless one of its event listeners calls stopPropagation() or stopImmediatePropagation(), either of which terminates propagation at once.

Calling preventDefault() during any stage of event flow cancels the event, meaning that any default action normally taken by the implementation as a result of the event will not occur.

You can use Event.cancelable to check if the event is cancelable. Calling preventDefault() for a non-cancelable event has no effect.

window.onKeydown = event => {
    /*
        if the control button is pressed, the event.ctrKey 
        will be the value  [true]
    */

    if (event.ctrKey && event.keyCode == 83) {
        event.preventDefault();
        // you function in here.
    }
}
七七 2024-08-13 22:16:14

我遇到了一个问题,仅在某些自定义操作(启用表单上禁用的输入字段)结束后才需要默认操作。我将默认操作 (submit()) 包装到自己的递归函数 (dosubmit()) 中。

var prevdef=true;
var dosubmit=function(){
    if(prevdef==true){
        //here we can do something else first//
        prevdef=false;
        dosubmit();
    }
    else{
        $(this).submit();//which was the default action
    }
};

$('input#somebutton').click(function(){dosubmit()});

I had a problem where I needed the default action only after some custom action (enable otherwise disabled input fields on a form) had concluded. I wrapped the default action (submit()) into an own, recursive function (dosubmit()).

var prevdef=true;
var dosubmit=function(){
    if(prevdef==true){
        //here we can do something else first//
        prevdef=false;
        dosubmit();
    }
    else{
        $(this).submit();//which was the default action
    }
};

$('input#somebutton').click(function(){dosubmit()});
人间☆小暴躁 2024-08-13 22:16:14

使用布尔值:

let prevent_touch = true;
document.documentElement.addEventListener('touchmove', touchMove, false);
function touchMove(event) { 
    if (prevent_touch) event.preventDefault(); 
}

我在渐进式 Web 应用程序中使用它来防止在某些“页面”上滚动/缩放,同时允许在其他“页面”上滚动/缩放。

Use a boolean:

let prevent_touch = true;
document.documentElement.addEventListener('touchmove', touchMove, false);
function touchMove(event) { 
    if (prevent_touch) event.preventDefault(); 
}

I use this in a Progressive Web App to prevent scrolling/zooming on some 'pages' while allowing on others.

安穩 2024-08-13 22:16:14

您可以设置为 2 个班级。将 JS 脚本设置为其中之一后,当您想要禁用脚本时,只需从该表单中删除带有绑定脚本的类即可。

HTML:

<form class="form-create-container form-create"> </form>   

JS

$(document).on('submit', '.form-create', function(){ 
..... ..... ..... 
$('.form-create-container').removeClass('form-create').submit();

});

You can set to form 2 classes. After you set your JS script to one of them, when you want to disable your script, you just delete the class with binded script from this form.

HTML:

<form class="form-create-container form-create"> </form>   

JS

$(document).on('submit', '.form-create', function(){ 
..... ..... ..... 
$('.form-create-container').removeClass('form-create').submit();

});
太傻旳人生 2024-08-13 22:16:14

在javacript中你可以简单地像这样

const form = document.getElementById('form');
form.addEventListener('submit', function(event){
  event.preventDefault();

  const fromdate = document.getElementById('fromdate').value;
  const todate = document.getElementById('todate').value;

  if(Number(fromdate) >= Number(todate)) {
    alert('Invalid Date. please check and try again!');
  }else{
    event.currentTarget.submit();
  }

});

in javacript you can simply like this

const form = document.getElementById('form');
form.addEventListener('submit', function(event){
  event.preventDefault();

  const fromdate = document.getElementById('fromdate').value;
  const todate = document.getElementById('todate').value;

  if(Number(fromdate) >= Number(todate)) {
    alert('Invalid Date. please check and try again!');
  }else{
    event.currentTarget.submit();
  }

});
静水深流 2024-08-13 22:16:14

作为恢复默认操作的唯一方法。

$('#some_link').unbind();

Worked as the only method to restore the default action.

$('#some_link').unbind();

我是男神闪亮亮 2024-08-13 22:16:14

这应该有效:

$('#myform').on('submit',function(e){
    if($(".field").val()==''){
        e.preventDefault();
    }
}); 

This should work:

$('#myform').on('submit',function(e){
    if($(".field").val()==''){
        e.preventDefault();
    }
}); 
安穩 2024-08-13 22:16:14
$('#my_elementtt').click(function(event){
    trigger('click');
});
$('#my_elementtt').click(function(event){
    trigger('click');
});
淑女气质 2024-08-13 22:16:14

我不确定你的意思是:但这里有一个类似(并且可能相同)问题的解决方案......

我经常使用 PreventDefault() 来拦截项目。但是:这不是唯一的拦截方法......通常您可能只需要一个“问题”,后面的行为会像以前一样继续或停止。
在最近的案例中,我使用了以下解决方案:

$("#content").on('click', '#replace', (function(event){
返回确认('您确定要这样做吗?')
}));

基本上,“防止默认”意味着拦截并执行其他操作:“确认”旨在用于......好吧 - 确认!

I'm not sure you're what you mean: but here's a solution for a similar (and possibly the same) problem...

I often use preventDefault() to intercept items. However: it's not the only method of interception... often you may just want a "question" following which behaviour continues as before, or stops.
In a recent case I used the following solution:

$("#content").on('click', '#replace', (function(event){
return confirm('Are you sure you want to do that?')
}));

Basically, the "prevent default" is meant to intercept and do something else: the "confirm" is designed for use in ... well - confirming!

痕至 2024-08-13 22:16:13

就我而言:

$('#some_link').click(function(event){
    event.preventDefault();
});

$('#some_link').unbind('click'); 是恢复默认操作的唯一方法。

如下所示:https://stackoverflow.com/a/1673570/211514

In my case:

$('#some_link').click(function(event){
    event.preventDefault();
});

$('#some_link').unbind('click'); worked as the only method to restore the default action.

As seen over here: https://stackoverflow.com/a/1673570/211514

美人如玉 2024-08-13 22:16:13

它相当简单

让我们假设您执行类似

document.ontouchmove = function(e){ e.preventDefault(); }

现在的操作将其恢复到原始情况,请执行以下操作...

document.ontouchmove = function(e){ return true; }

来自此 网站

Its fairly simple

Lets suppose you do something like

document.ontouchmove = function(e){ e.preventDefault(); }

now to revert it to the original situation, do the below...

document.ontouchmove = function(e){ return true; }

From this website.

旧伤还要旧人安 2024-08-13 22:16:13

不可能恢复 preventDefault() 但你可以做的就是欺骗它:)

<div id="t1">Toggle</div>
<script type="javascript">
$('#t1').click(function (e){
   if($(this).hasClass('prevented')){
       e.preventDefault();
       $(this).removeClass('prevented');
   }else{
       $(this).addClass('prevented');
   }
});
</script>

如果你想更进一步,你甚至可以使用触发按钮来触发事件。

It is not possible to restore a preventDefault() but what you can do is trick it :)

<div id="t1">Toggle</div>
<script type="javascript">
$('#t1').click(function (e){
   if($(this).hasClass('prevented')){
       e.preventDefault();
       $(this).removeClass('prevented');
   }else{
       $(this).addClass('prevented');
   }
});
</script>

If you want to go a step further you can even use the trigger button to trigger an event.

開玄 2024-08-13 22:16:13
function DoPrevent(e) {
  e.preventDefault();
  e.stopPropagation();
}

// Bind:
$(element).on('click', DoPrevent);

// UnBind:
$(element).off('click', DoPrevent);
function DoPrevent(e) {
  e.preventDefault();
  e.stopPropagation();
}

// Bind:
$(element).on('click', DoPrevent);

// UnBind:
$(element).off('click', DoPrevent);
〗斷ホ乔殘χμё〖 2024-08-13 22:16:13

在某些情况下*,您最初可以返回 false 而不是 e.preventDefault(),然后当您想要恢复默认值时返回 true

*意思是当您不介意事件冒泡并且不将 e.stopPropagation()e.preventDefault() 一起使用时

另请参阅 类似的问题(也在堆栈溢出中)

或者在复选框的情况下,你可以有一些东西喜欢:

$(element).toggle(function(){
  $(":checkbox").attr('disabled', true);
  },
function(){
   $(":checkbox").removeAttr('disabled');
}) 

in some cases* you can initially return false instead of e.preventDefault(), then when you want to restore the default to return true.

*Meaning when you don't mind the event bubbling and you don't use the e.stopPropagation() together with e.preventDefault()

Also see similar question (also in stack Overflow)

or in the case of checkbox you can have something like:

$(element).toggle(function(){
  $(":checkbox").attr('disabled', true);
  },
function(){
   $(":checkbox").removeAttr('disabled');
}) 
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文