简体   繁体   English

jQuery-单击事件绑定并在页面加载时启动

[英]jquery - click event binding and launching on page load

Happy Friday errybody! 星期五快乐errybody!

Alright, so I'm having trouble binding a 'click' event when a particular class of divs load. 好的,因此在加载特定类的div时绑定“ click”事件时遇到麻烦。

What happens is that the 'click' event is being triggered on load. 发生的情况是“点击”事件是在加载时触发的。 I've even tried unbinding before I bind. 在绑定之前,我什至尝试解除绑定。

onAppLoad = function() {
  console.log('span 4 loaded');

  hovering = function() {
    console.log('hovering!');
  }

  $.each($('.span4 > a'), function() {
    var whichApp = $(this).attr('data-content');

    $(this).unbind('click');
    $(this).bind('click', hovering());

  })   
}

$('.span4').load(onAppLoad());

You have a syntax error: 您有语法错误:

 $(this).bind('click', hovering());

Here you are calling the function hovering while what you want it to give the reference. 在这里,您要在函数hovering时调用其希望提供引用的内容。 Try this : 尝试这个 :

 $(this).bind('click', hovering);

Your .load() is wrong too (for the same reason). 您的.load()也是错误的(出于相同的原因)。

$('.span4').load(onAppLoad);

Side note about the .each . 关于.each When you are iterating a jquery object, you should write it like that : 当迭代一个jquery对象时,应该这样写:

$('.span4 > a').each(function() {})

Couple of things I see i your code: 我看到的几件事是您的代码:
1. You're missing a closing bracket for onAppLoad() 1.您缺少onAppLoad()的结尾括号
2. Change $(this).bind('click', hovering()); 2.更改$(this).bind('click', hovering()); to $(this).bind('click', hovering); $(this).bind('click', hovering);
3. Change $('.span4').load(onAppLoad()); 3.更改$('.span4').load(onAppLoad()); to $('.span4').load(onAppLoad); $('.span4').load(onAppLoad);

Out of curiosity, why not put all event handlers in a $(document).ready() event? 出于好奇,为什么不将所有事件处理程序放在$(document).ready()事件中?

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

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