一旦我触发了event . preventdefault(),我如何再次恢复默认操作?


当前回答

在一个同步流中,你只在需要的时候调用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,可以确保上述流是同步的

其他回答

我认为“相反”应该是模拟一个事件。你可以使用.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');

好的!它适用于点击事件:

$("#submit").click(function(event){ 
  
   event.preventDefault();

  // -> block the click of the sumbit ... do what you want

  // the html click submit work now !
  $("#submit").unbind('click').click(); 

});

在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()之后;

这里没有一个解决方案对我有帮助,我这样做是为了解决我的情况。

<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();
}
event.preventDefault(); //or event.returnValue = false;

及其反义词(标准):

event.returnValue = true;

来源: https://developer.mozilla.org/en-US/docs/Web/API/Event/returnValue