Access event to call preventdefault from custom function originating from onclick attribute of tag

前端 未结 11 2622
粉色の甜心
粉色の甜心 2020-11-28 04:07

I have links like this:

click
c         


        
11条回答
  •  悲&欢浪女
    2020-11-28 04:16

    I believe you can pass in event into the function inline which will be the event object for the raised event in W3C compliant browsers (i.e. older versions of IE will still require detection inside of your event handler function to look at window.event).

    A quick example.

    function sayHi(e) {
       e.preventDefault();
       alert("hi");
    }
    Click to say Hi

    1. Run it as is and notice that the link does no redirect to Google after the alert.
    2. Then, change the event passed into the onclick handler to something else like e, click run, then notice that the redirection does take place after the alert (the result pane goes white, demonstrating a redirect).

提交回复
热议问题