How to pass an event object to a function in Javascript?

前端 未结 3 976
梦毁少年i
梦毁少年i 2020-12-07 21:44
3条回答
  •  死守一世寂寞
    2020-12-07 22:32

    1. Modify the definition of the function check_me as::

       function check_me(ev) {
      
    2. Now you can access the methods and parameters of the event, in your case:

       ev.preventDefault();
      
    3. Then, you have to pass the parameter on the onclick in the inline call::

       
      

    A useful link to understand this.


    Full example:

    
    
      
        
      
      
        
      
    
    









    Alternatives (best practices):

    Although the above is the direct answer to the question (passing an event object to an inline event), there are other ways of handling events that keep the logic separated from the presentation

    A. Using addEventListener:

    
    
      
      
      
        
    
        
        
      
    
    

    B. Isolating Javascript:

    Both of the above solutions are fine for a small project, or a hackish quick and dirty solution, but for bigger projects, it is better to keep the HTML separated from the Javascript.

    Just put this two files in the same folder:

    • example.html:
    
    
      
      
      
        
    
        
        
      
    
    
    • example.js:
    function check_me(ev) {
        ev.preventDefault();
        alert("Hello World!")
    }
    document.getElementById("my_button").addEventListener("click", check_me);
    

提交回复
热议问题