[英]How to use an external function in event handler in JQuery
I want to do something like this:我想做这样的事情:
$(div).bind('click', myFunctionWithManyManyLinesOfCode(param) );
.....
function myFunctionWithManyManyLinesOfCode(args){
//50 lines of Code
}
If I do this the function is executed when the code reaches the point and doesn't execute on clicks.如果我这样做,则 function 会在代码到达该点并且不会在点击时执行。
If I include the code from the function myFunctionWithManyManyLinesOfCode in the bind method it will be a mess of code.如果我在绑定方法中包含来自 function myFunctionWithManyManyLinesOfCode 的代码,那将是一团乱麻。
Also, I've tried this, but I cannot reference variables, they are undefined另外,我试过这个,但我不能引用变量,它们是未定义的
$(div).bind('click', function() {myFunctionWithManyManyLinesOfCode(param)} );
You can pass whatever data you want to in the following way.您可以通过以下方式传递您想要的任何数据。
This should do the trick for you.这应该为您解决问题。 If something is unclear please write a comment.
如果有不清楚的地方,请写评论。
Edit: As stated in the comments you should use on and not bind.编辑:如评论中所述,您应该使用而不是绑定。
function myFunction(e){ console.log(e.data.id); } $('#example').on('click',{id: "WHATEVER"}, myFunction);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <button id="example">Test</button>
First of all, 50 lines of code are too much for one function and should be divided into smaller methods, but you can use this method:首先,50行代码对于一个function来说太多了,应该分成更小的方法,但是你可以使用这种方法:
var hello = () => {
alert(123)
}
$("p").click(hello);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.