Can you extend the val() function in jQuery?

杀马特。学长 韩版系。学妹 提交于 2019-12-04 14:05:59

Try

$.fn.xval = function () {
    return this.toggleClass(arguments.length).val.apply(this, arguments);
};

Demo: http://jsfiddle.net/mattball/v9YFu/

You could do this:

var oldVal = $.fn.val;
$.fn.val = function(value) {
    $(this).addClass("dark");
    return oldVal.apply(this, arguments);
};

But I'd strongly discourage you to use it because setting an element's value has nothing to do with setting CSS properties. val sets values, and that's it. What you could do is this:

$("#someInput").change(function() {
    if ($(this).text().length > 0) {
        $(this).addClass("dark");
    } else {
        $(this).removeClass("dark");
    }
});

The function you pass to change will be called, whenever the value is changed - programmatically or by the user (see documentation). This way the code gets much more readable and comprehensible, what makes it easier to debug too.

$.fn.darkVal = function (value) { return this.addClass('dark').val(value); };

As pointed out by other answers, you can extend (overwrite) the val() function but it's not good practice to hardcode unrelated behaviour into it.

However, I find that a handy way of triggering something when the value is changed programatically is to overwrite the val() function and trigger the change event of your element - BUT ONLY IF SPECIFIED by that element.

You can define that request by adding a data attribute (or class etc.) to your element like so:

<!-- Add the data-trigger-change attribute -->
<input data-trigger-change class="dark-when-changed" name="test" value="123">

Then, your new val function can check for that attribute.

const fnVal = $.fn.val;

$.fn.val = function(value) {
	// check if the value is actually changing
	let changed = typeof value!=='undefined' && typeof $(this)[0] !=='undefined' && value !== $(this)[0].value;
	// change the value by the standard method
	let $return = fnVal.apply(this, arguments);
	// if this element wants to trigger the change method (and it has actually changed)
	if(changed && $(this).is('[data-trigger-change]')) {
		// trigger the change method
		$(this).trigger("change");
		// return the original response
		return $return;
	}
	// return the original response without doing anything else
	return $return;
};

...and then you can write a change handler to do whatever you like:

$(document).on('change','input.dark-when-changed',function(){
  $(this).addClass('dark');
});

WARNING! Doing this can result in an infinite loop if you change the value in your change handler using val(), obviously. If you really needed to, you could avoid that by using $('input.dark-when-changed')[0].value = 'blah';

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!