问题描述
有没有办法轻松覆盖 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()
.
推荐答案
我知道这是一个古老的主题,但它在谷歌搜索中是第一个,答案并不完全正确......
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
的升级答案.
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);
如果你想传递所有参数,你也可以使用 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() 函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!