Override jQuery .val() function?

前端 未结 6 476
盖世英雄少女心
盖世英雄少女心 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:17

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

    (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_get and $val_set:

    
    
    
    
    

    This is useful for creating components that orchestrate multiple controls.

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

提交回复
热议问题