选定类上的Jquery绑定事件

时间:2021-10-16 23:00:09

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 -

在jquery中可以将事件绑定到具有特定类的控件组吗?在我看来,这是不可能的。我有点谷歌,所有这些都与事件无关。我的代码是这样的

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

2 个解决方案

#1


11  

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

您的代码应该可以工作,这里有一个实际的示例:http://jsfiddle.net/g3GsE/

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

确保你的代码是像这样包装的,直到document。ready:

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

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.

如果没有这个,它将立即执行,类=“numonly”元素将不会出现在那里……代码需要等待直到文档。准备好了,它会在元素出现后触发,这样选择器就会找到它们。

#2


1  

Yes this code should work just fine. Just make sure you double check it on the server when submitted. So those who disabled JS can't get around your limitation.

是的,这段代码应该可以正常工作。只要确保在提交时在服务器上对其进行双重检查即可。所以那些禁用JS的人无法绕过你的限制。

#1


11  

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

您的代码应该可以工作,这里有一个实际的示例:http://jsfiddle.net/g3GsE/

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

确保你的代码是像这样包装的,直到document。ready:

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

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.

如果没有这个,它将立即执行,类=“numonly”元素将不会出现在那里……代码需要等待直到文档。准备好了,它会在元素出现后触发,这样选择器就会找到它们。

#2


1  

Yes this code should work just fine. Just make sure you double check it on the server when submitted. So those who disabled JS can't get around your limitation.

是的,这段代码应该可以正常工作。只要确保在提交时在服务器上对其进行双重检查即可。所以那些禁用JS的人无法绕过你的限制。