如何将阻止默认调用传递给其他事件

How to pass preventDefault call to other event?

本文关键字:其他 事件 调用 默认      更新时间:2023-09-26

当事件发生时,其名称会触发其他一些事件。在某些情况下,第二个处理程序可以调用 preventDefault 。如何将此调用传递到原始事件?

https://jsfiddle.net/edgv8qur/1/

$("button").click(function (event) {
  $("body").trigger("some-custom-event");
  // If the custom event was prevented, prevent original one too
  if (true) { // How to check?
    event.preventDefault();
  }
})
$("body").on("some-custom-event", function (event) {
  if (Math.random() > .5) {
    console.log("prevent");
    event.preventDefault();
  } else {
    console.log("allow");
  }
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<button>Test</button>

PS:俄语中的相同问题。

您可以将参数数组传递给trigger()这些参数将传递给 on() 中设置的事件处理程序。以下是您的操作方法:

$("button").click(function (event) {
    function cb(prevent) {
        // If the custom event was prevented, prevent original one too
        if (prevent) {
            event.preventDefault();
        }
    }
    $("body").trigger("some-custom-event", [cb]);
})
$("body").on("some-custom-event", function (event, cb) {
  if (Math.random() > .5) {
    console.log("prevent");
    event.preventDefault();
    cb(true);
  } else {
    console.log("allow");
  }
})

您可以在此处了解有关trigger()的更多信息。

更新:

如果您不想编辑处理程序,这是要走的路:

$("button").click(function (event) {
    var event = jQuery.Event('some-custom-event');
    $("body").trigger(event);
    if (event.isDefaultPrevented()) {
        event.preventDefault();
        console.log("Prevented");
    } else {
        console.log("Allowed");
    }
})
$("body").on("some-custom-event", function (event) {
    if (Math.random() > .5) {
        console.log("prevent");
        event.preventDefault();
    } else {
        console.log("allow");
    }
})

event.isDefaultPrevented() 返回是否曾经在此事件对象上调用过 event.preventDefault()。