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


当前回答

我建议采用以下模式:

document.getElementById("foo").onsubmit = function(e) {
    if (document.getElementById("test").value == "test") {
        return true;
    } else {
        e.preventDefault();
    }
}

<form id="foo">
    <input id="test"/>
    <input type="submit"/>
</form>

...除非我遗漏了什么。

http://jsfiddle.net/DdvcX/

其他回答

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

});

这段代码为我重新实例化事件后,我已经使用:

event.preventDefault(); to disable the event.


event.preventDefault = false;

这里有一些有用的东西……

首先,我们将单击链接,运行一些代码,然后执行默认操作。这可以使用event实现。看看吧。在这里,我们将尝试在一个新选项卡上访问谷歌,但在我们需要运行一些代码之前。

<a href="https://www.google.com.br" target="_blank" id="link">Google</a>

<script type="text/javascript">
    $(document).ready(function() {
        $("#link").click(function(e) {

            // Prevent default action
            e.preventDefault();

            // Here you'll put your code, what you want to execute before default action
            alert(123); 

            // Prevent infinite loop
            $(this).unbind('click');

            // Execute default action
            e.currentTarget.click();
        });
    });
</script>

这是我用来设置的:

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

要撤消它:

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

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

<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();
}