简体   繁体   English

在主函数中调用点击函数

[英]Calling click functions inside a main function

I just wanted to know about any downsides to calling click functions inside a main function rather than in the $(document).ready(function() {}); 我只是想知道在主函数而不是$(document).ready(function() {});调用click函数的任何缺点$(document).ready(function() {}); . This is what i mean 这就是我的意思

 function tester() { $('.className-1').click(function() { var cmtpid = $(this).attr('data-cmtpid'); alert(cmtpid); }); $('.className-2').click(function() { var pid = $(this).attr('data-pid'); alert(pid); }); } tester(); 

UPDATE : the tester() function will only be called once, this is all mainly because I want to avoid inline html onclick="" 更新: tester()函数将仅被调用一次,这主要是因为我想避免内联html onclick=""

Since I noticed you're using jQuery. 由于我注意到您正在使用jQuery。 Perhaps consider adding unbind("click") after the selector to ensure you don't accidentally bind the click more than once causing multiple executions upon click. 也许考虑在选择器之后添加unbind("click") ,以确保您不会意外地绑定多次单击,从而导致多次单击。

Also there isn't any REAL downside but I would HIGHLY recommended putting that java-script at the very end of your html document to ensure the DOM is loaded. 也没有任何真正的缺点,但我会强烈建议把该Java的脚本放在HTML文档的最后,以确保DOM被加载。

Example: 例:

$('.className-1').unbind("click").click(function(){

});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM