Jquery绑定事件在选定的类 [英] Jquery binding event on selected class

查看:193
本文介绍了Jquery绑定事件在选定的类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以在jQuery中将事件绑定到具有某个类的一组控件?在我看来,它不能。我有一点谷歌,所有这些都与事件无关。以下是我的代码如何 -

Is it achievable in jquery to bind an event to a group of control that has certain class? It seems to me, it can't. I google a bit and all that came up are nothing to do with events. Here's how my code looks -

$('.numonly').bind('keypress',function(event){
    if (event.which > 31 && (event.which < 48 || event.which > 57)) return false;
});


推荐答案

你的代码应该工作,这里是一个例子行动: http://jsfiddle.net/g3GsE/

Your code should work, here's an example of it in action: http://jsfiddle.net/g3GsE/

确保您的代码是这样包装的,所以直到 document.ready 才执行:

Make sure that your code is wrapped like this so it doesn't execute until document.ready:

$(function() {
  $('.numonly').bind('keypress',function(event){
    if (event.which > 31 && (event.which < 48 || event.which > 57)) return false;
  });
});

没有这个,它会立即执行, class =numonly / code>元素不会在那里找到...代码需要等到document.ready,所以它在元素之后触发,所以选择器找到它们。

Without this, it would execute immediately and the class="numonly" elements won't be there to find yet...the code needs to wait until document.ready so it fires after the elements are there, so the selector finds them.

这篇关于Jquery绑定事件在选定的类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆