首页 > 解决方案 > 在主函数中调用点击函数

问题描述

我只是想知道在 main 函数中调用 click 函数而不是在$(document).ready(function() {});. 这就是我的意思

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();

更新:该tester()函数只会被调用一次,这主要是因为我想避免内联htmlonclick=""

标签: javascriptjquery

解决方案


因为我注意到你正在使用 jQuery。也许考虑unbind("click")在选择器之后添加,以确保您不会意外地多次绑定单击,从而导致单击时多次执行。

也没有任何真正的缺点,但我强烈建议将该 java 脚本放在 html 文档的最后,以确保加载 DOM。

例子:

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

});

推荐阅读