jQuery: How do I use event.preventDefault() with custom events?

后端 未结 5 537
逝去的感伤
逝去的感伤 2021-02-01 02:48

How can I know in my triggering code that preventDefault has been called?

$(document).trigger(\'customEvent\', params);
if (/* ??? */)
    doDefault         


        
5条回答
  •  慢半拍i
    慢半拍i (楼主)
    2021-02-01 03:27

    In case someone needs it, as I did. Important the 2nd constructor-parameter:

    Pure JS:

    var event = new CustomEvent("close", { "cancelable": true });
    // now event listeners can prevent default behavior
    element.onclose(event);
    // or: element.dispatchEvent(event);
    
    if (!event.defaultPrevented)
        defaultBehavior();
    

提交回复
热议问题