0

I would like to put the script inside an anonymous function in a separate function so that I can use it on various elements without duplicating the code. The script needs to have access to both this and e. myID1 is using an anonymous function before trying to use a separate function. myID2 works, but I have a feeling isn't the preferred way. myID3 has access to this, but I couldn't figure out how to access e. How is this done?

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> 
<html xmlns="http://www.w3.org/1999/xhtml"> 
    <head> 
        <meta http-equiv="content-type" content="text/html; charset=ISO-8859-1" /> 
        <title>Testing</title>  
        <script src="http://code.jquery.com/jquery-latest.js" type="text/javascript"></script> 
        <script type="text/javascript">
        function otherFunction2(e,This){console.log(e,This);} 
        function otherFunction3(){console.log(this);} 
            $(function(){
                $('#myID1').on("click", "a.myClass", function(e){console.log(e,this);});
                $('#myID2').on("click", "a.myClass", function(e){otherFunction2(e,this);});
                $('#myID3').on("click", "a.myClass", otherFunction3); //Can't access e
            });
        </script>
    </head>

    <body>
        <div id="myID1"><a href="javascript:void(0)" class="myClass">Click Me</a></div>
        <div id="myID2"><a href="javascript:void(0)" class="myClass">Click Me</a></div>
        <div id="myID3"><a href="javascript:void(0)" class="myClass">Click Me</a></div>
    </body> 
</html> 
4

3 に答える 3

2

に渡された関数 (または関数参照) はon、1 つのパラメーターで呼び出されます: eventObject. 好きなように参照できます...e大丈夫です。

次に、this(パラメーターではなく) 暗黙的に定義されている の値が、イベントがトリガーされた要素として自動的に設定されます。したがって、参照を渡したい場合は、次のように参照を設定します。

function someFunction(e) {
    console.log(e, this);
}

パラメータを1 つ設定するだけで、this自動的に適切に定義されます。

#myID2とで行うように、イベント ハンドラーから別の関数を呼び出したい場合は、someFunction2それらを明示的に渡すか (持っているように)、 を使用できますcall

参考文献:

于 2013-04-29T16:33:49.357 に答える