一旦我触发了event . 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");
    }
});

现在,通过使用命名空间,您可以添加多个这样的事件,并能够根据您的需要删除它们。虽然提交可能不是最好的例子,但这可能在点击或按键或其他方面派上用场。

其他回答

这是我用来设置的:

$("body").on('touchmove', function(e){ 
    e.preventDefault(); 
});

要撤消它:

$("body").unbind("touchmove");

为了执行异步调用,我不得不在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();
    });
});

在一个同步流中,你只在需要的时候调用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();
});

这不是对问题的直接回答,但它可能会帮助到一些人。我的观点是,你只根据某些条件调用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

});