本文介绍了重写jQuery .val()函数吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有一种方法可以轻松地覆盖jQuery的val()函数?

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

我要覆盖它的原因是,我希望在每次为元素设置值时都添加一些处理.而且我不想创建另一个自定义值设置器,例如myVal().

The reason I want to override it is that I want to add some processing each time a value is set for an element. And I don't want to make another custom value setter, such as myVal().

推荐答案

我知道这是一个古老的主题,但它是google搜索中的第一个主题,答案并不完全正确...

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

例如,如果您在控制台$('#myinput').val()中尝试,则应获取#myinput的值.

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

但是,如果您执行$('#myinput').val(undefined),则应设置#myinput的值!(使用当前答案及其注释,您将不会设置#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)

这是使用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);

如果要传递所有参数,也可以使用apply

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);

希望对您有帮助!

这篇关于重写jQuery .val()函数吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

05-27 18:54