覆盖 jQuery .val() 函数?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2059907/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 12:41:04  来源:igfitidea点击:

Override jQuery .val() function?

jqueryjquery-plugins

提问by 7wp

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

有没有办法轻松覆盖jQuery的val()功能?

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().

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

采纳答案by Benjamin SCETBUN

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.

例如,如果您在控制台中尝试,$('#myinput').val()您应该获得#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)

但是如果你这样做$('#myinput').val(undefined)你应该设置#myinput的值!(根据当前的答案和它的评论,你不会设置#myinput的值)

Here is an upgraded answer that use arguments.

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

如果你想传递所有参数,你也可以使用 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!

我希望它有帮助!

回答by CMS

You can store a reference to the original valfunction, then override it and do your processing, and later invoke it with call, to use the right context:

您可以存储对原始val函数的引用,然后覆盖它并进行处理,然后call使用调用它以使用正确的上下文:

(function ($) {
  var originalVal = $.fn.val;
  $.fn.val = function(value) {
    if (typeof value != 'undefined') {
      // setter invoked, do processing
    }
    return originalVal.call(this, value);
  };
})(jQuery);

Note that you can distinguish between a getter call $(selector).val();and a setter call $(selector).val('new value');just by checking if the valueargument is undefinedor not.

请注意,您可以通过检查参数是否存在来区分 getter 调用$(selector).val();和 setter 调用。$(selector).val('new value');valueundefined

回答by Roman

I know the problem is old but just to give a full solution. In order for both the jQuery.val() and the jQuery.val(value) to work after override you need to override it properly and separately. Because when calling jQuery.val() then originalVal.call(this, value); will not work correctly.

我知道这个问题很老,但只是为了给出一个完整的解决方案。为了使 jQuery.val() 和 jQuery.val(value) 在覆盖后工作,您需要正确且单独地覆盖它。因为当调用 jQuery.val() 然后 originalVal.call(this, value); 将无法正常工作。

To do it in a correct way you need to do something like that when getting the value: originalVal.call(this);

要以正确的方式执行此操作,您需要在获取值时执行类似操作: originalVal.call(this);

Here is a site where everything is explained: http://extremedev.blogspot.com/2012/01/override-jqueryval-and-jqueryvalvalue.html

这是一个解释一切的网站:http: //extremedev.blogspot.com/2012/01/override-jqueryval-and-jqueryvalvalue.html

Regards, Roman

问候, 罗马

回答by Reid

If I am understanding you right, something like this should do the trick just fine:

如果我理解正确的话,这样的事情应该可以解决问题:

jQuery.fn.val = function (new_val) {
    alert("You set a val! How wonderful!");
    this.value = new_val;
};

Just make sure you include the regular functionality: getting values of selects and so on. Just stick that code afterafter the regular jQuery library.

只需确保包含常规功能:获取选择的值等。只要坚持这些代码之后的常规jQuery库之后。

回答by Raphael

With this code you can override the "get" and "set" of .val()for specific elements:

使用此代码,您可以覆盖.val()特定元素的“get”和“set” :

(function () {

    var __val = $.fn.val;
    $.fn.val = function (value) {
        if (this[0] && (this[0].$val_get || this[0].$val_set)) {
            if (arguments.length === 0) return this[0].$val_get();
            else return this[0].$val_set(value) || this;
        }
        return __val.apply(this, arguments);
    };

})();

Now you have to create two function properties on the DOM element - $val_getand $val_set:

现在您必须在 DOM 元素上创建两个函数属性 -$val_get$val_set

<input type="text" id="myInput" />
<input type="text" id="someOtherInput" />

<script>

    $('#myInput')[0].$val_get = function () {
        console.log('Got value from myInput!');
        return this.value;
    };

    $('#myInput')[0].$val_set = function (value) {
        console.log('Set value of myInput!');
         this.value = value;
    }

    //----

    $('#myInput').val('Hello!'); //Console: "Got value from myInput!"
    $('#myInput').val(); //Hello! | Console: "Set value to myInput!"

    $('#someOtherInput').val('Hello!'); //Console: ""
    $('#someOtherInput').val(); //Hello! | Console: ""

</script>

This is useful for creating components that orchestrate multiple controls.

这对于创建编排多个控件的组件很有用。

JsFiddle: https://jsfiddle.net/oj4gt2ye/6/

JsFiddle:https://jsfiddle.net/oj4gt2ye/6/

回答by ungalcrys

I have something to add to CMS answer, my implementation would differ and be like this:

我有一些东西要添加到 CMS 答案中,我的实现会有所不同,如下所示:

(function ($) { var fnVal = $.fn.val;
    $.fn.val = function(value) {
        if (typeof value == 'undefined') {
            return fnVal.call(this);
        }
        var result = fnVal.call(this, value);
        $.fn.change.call(this);
        // here you can add some more implementation
        return result;
    };
})(jQuery);

observe the $.fn.change.call(this);will be called before exiting the val('') function this will trigger also the .change() on each val('') assignment.

观察$.fn.change.call(this); 将在退出 val('') 函数之前被调用,这也将在每个 val('') 赋值上触发 .change()。