Override jQuery .val() function?

前端 未结 6 477
盖世英雄少女心
盖世英雄少女心 2020-12-01 10:41

Is there a way to easily override jQuery\'s val() function?

The reason I want to override it is that I want to add some processing each time a value is

6条回答
  •  误落风尘
    2020-12-01 11:26

    I know it's an old subject but it's first in google search and the answer is not completely right...

    For example if you try in the console $('#myinput').val() you should get the value of #myinput.

    But if you do $('#myinput').val(undefined) you should set the value of #myinput!( With the current answer and the comments of it, you will not set the value of #myinput)

    Here is an upgraded answer that use arguments.

    (function ($) {
      var originalVal = $.fn.val;
      $.fn.val = function(value) {
        if (arguments.length >= 1) {
          // setter invoked, do processing
          return originalVal.call(this, value); 
        }
        //getter invoked do processing
        return originalVal.call(this);
      };
    })(jQuery);
    

    if you want to pass all the arguments you can also use apply

    (function ($) {
      var originalVal = $.fn.val;
      $.fn.val = function(value) {
        if (arguments.length >= 1) {
          // setter invoked, do processing
        } else {
          //getter invoked do processing
        }
        return originalVal.apply(this, arguments);
      };
    })(jQuery);
    

    I hope it help!

提交回复
热议问题