Jquery为多个相同的类选择器分配函数

时间:2014-03-11 03:36:22

标签: jquery arrays validation

我的代码看起来像这样:

 <script type="text/javascript">
     $(document).ready(function () {
         $(".numberinput").forceNumeric();
     });


     // forceNumeric() plug-in implementation
     jQuery.fn.forceNumeric = function () {

         return this.each(function () {
             $(this).keydown(function (e) {
                 var key = e.which || e.keyCode;

                 if (!e.shiftKey && !e.altKey && !e.ctrlKey &&
                 // numbers   
                     key >= 48 && key <= 57 ||
                 // Numeric keypad
                     key >= 96 && key <= 105 ||
                 // comma, period and minus, . on keypad
                    key == 190 || key == 188 || key == 109 || key == 110 ||
                 // Backspace and Tab and Enter
                    key == 8 || key == 9 || key == 13 ||
                 // Home and End
                    key == 35 || key == 36 ||
                 // left and right arrows
                    key == 37 || key == 39 ||
                 // Del and Ins
                    key == 46 || key == 45)
                     return true;

                 return false;
             });
         });
     }
 </script>

在文档就绪时,我分配了这样的函数 $(“。numberinput”)。forceNumeric(); 这只适用于一个输入。如何将函数分配给具有相同类名的多个输入?

我试过这个:

$(".numberinput").each(function(){ $(this).forceNumeric(); }); 

但这不起作用。任何帮助都会很棒。

由于

1 个答案:

答案 0 :(得分:1)

该插件设置为隐式处理jQuery集合中的所有元素(您可以通过return this.each(function(){ })告诉。

所以你应该可以使用$(".numberinput").forceNumeric()