简体   繁体   English

自制jQuery插件已触发但不起作用

[英]Self-made jQuery plugin triggered but not working

I wrote a simple plugin to validate if input fields that needs to be number are indeed numbers. 我写了一个简单的插件来验证需要输入数字的字段是否确实是数字。

The plugin can be successfully loaded and triggered, but it doesn't do anything. 该插件可以成功加载和触发,但不会执行任何操作。 However, if I manually type $(selector).validateNum(); 但是,如果我手动键入$(selector).validateNum();。 in the console, it works perfectly. 在控制台中,它可以完美运行。 Anyone knows why? 有人知道为什么吗?

Please check this jsBin for the live version: 请检查此jsBin的实时版本:

jsBin: http://jsbin.com/tusunuweto/1/edit?html,js,console,output jsBin: http ://jsbin.com/tusunuweto/1/edit?html、js,控制台,输出

Code below: 代码如下:

  $.fn.validateNum = function () {
    console.log('validation started');
    var numInputFields = this.find('input.number');

    $(numInputFields).each(function () {
      if ( isNaN( Number( $(this).val() ) ) ) {
        $(this).keyup(function () {
          alert("This field must be a number");
        });
      }
    });
  };

In my index.html file: 在我的index.html文件中:

<script type="text/javascript">

  $(function() {
    $('#selector').validateNum();
  });

</script>

You need to move your isNaN check into the click handler, I also added a regex to remove non numbers. 您需要将isNaN支票移到点击处理程序中,我还添加了一个正则表达式来删除非数字。

This works, but if you want to do validation like this, you might want to look into a library like .validate 这行得通,但是如果您要进行这样的验证,则可能需要查看.validate这样的库

  $(function () { $.fn.validateNum = function () { console.log('validation started'); var numInputFields = this.find('input.number'); $(numInputFields).each(function () { $(this).keyup(function () { // you need to move your isNaN check into the click handler if (isNaN(Number($(this).val()))) { $(this).val( $(this).val().replace(/[^0-9.]/g, "") ); // added this to remove non-numbers alert("This field must be a number"); } }); }); }; $(".testPlugin").validateNum(); }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div class="testPlugin"> <input class="number" /> 

A couple of issues I see 我看到的几个问题

You're not chaining properly 您没有正确链接

This isn't inherently bad (because .find does work the way you've used it) but it could afford to be more explicit. 这并不是天生的坏事(因为.find确实可以按照您使用它的方式工作),但是它可以变得更加明确。 For example, if you call $(".foo, .bar").validateNum() it should be clear that it's going to find inputs in each selected element 例如,如果调用$(".foo, .bar").validateNum()则应该清楚它将在每个选定元素中查找输入

You'll see this pattern very commonly in other community plugins 您会在其他社区插件中看到这种模式

$.fn.myPlugin = function() {
  // `this` is the jQuery object that matches the selected elements

  // don't forget `return` to make your plugin chainable
  return this.each(function() {
    // iterate through the selected elements performing some operation
  });
};

But! 但! as you'll see next, we don't even need to use .find at all! 如您接下来将看到的,我们甚至根本不需要使用.find


You're not using event delegation 您没有使用事件委托

You're specifically binding a .keyup listener to each input. 您专门将.keyup侦听器绑定到每个输入。 If there's a lot of inputs on your page, this could become very resource usage intensive. 如果页面上有很多输入,这可能会占用大量资源。

This method uses delegation so you're not binding a listener to every single input 此方法使用委托,因此您不必将侦听器绑定到每个输入

$.fn.validateNum = function() {
  console.log("validation started");
  return this.each(function() {
    $(this).on("keyup", ".number", function(event) {
      var num = parseInt($(this).val(), 10);
      if (isNaN(num)) {
        alert("This field must be a number");
      }
    });
  });
};

$(".testPlugin").validateNum();

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

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