addEventListener Two Functions

前端 未结 3 621
半阙折子戏
半阙折子戏 2020-12-05 18:35

How can I make it so that addEventListener() has two functions inside it?

I have tried finding my own solution, but none seem not to work. Please give me example if

相关标签:
3条回答
  • 2020-12-05 18:51

    Two major differences between the older model and the newer DOM Level 2 event model is that 1) the newer model isn’t as dependent on a specific event handler property, and 2) you can register multiple event handler functions for any one event on any one object.(From: Learning JavaScript) For example:

    <!DOCTYPE html>
    <html>
        <body>
            <div id="myElement"> Please click here.</div>
            <script>
                function func0() {
                    alert("Function0 is called");
                }
                function func1() {
                    alert("Function1 is called");
                }
                document.getElementById("myElement").addEventListener("click", func0, true);
                document.getElementById("myElement").addEventListener("click", func1, true);
            </script>
        </body>
    </html>
    

    As, even you can remove a specific event handler function for one event on any one object. For example:

    <!DOCTYPE html>
    <html>
        <body>
            <div id="myElement"> Please click here.</div>
            <script>
                function func0() {
                    alert("Function0 is called");
                }
                function func1() {
                    alert("Function1 is called");
                }
                document.getElementById("myElement").addEventListener("click", func0, true);
                document.getElementById("myElement").addEventListener("click", func1, true);
                document.getElementById("myElement").removeEventListener("click", func0, true);
            </script>
        </body>
    </html>
    
    0 讨论(0)
  • 2020-12-05 19:01

    Wrap your functions in a function.

    const invokeMe = () => console.log('I live here outside the scope');
    const alsoInvokeMe = () => console.log('I also live outside the scope'); 
    
    element.addEventListener('event',() => {    
         invokeMe();
         alsoInvokeMe();    
    });
    
    0 讨论(0)
  • 2020-12-05 19:07

    Wrap your functions in a function. But need to send all params from addEventListener callback (paramter event)

    const callbackOne = (...props) => {
        console.log('callbackOne', ...props)
    };
    const callbackTwo = (...props) => {
        console.log('callbackTwo', ...props)
    };
    
    element.addEventListener('eventName',(...props) => {    
         callbackOne(...props);  
         callbackTwo(...props);
    });
    

    You

    0 讨论(0)
提交回复
热议问题