所以我尝试使用以下代码修改原始jQuery的val()方法
(function ($) {
var original_val = jQuery.fn.val;
jQuery.fn.val = function( value ) {
var elem = this[0], val = undefined;
// Set for value first, if its undefined
val = value ? value : "";
if (elem){
if (elem.hasAttribute('thisattribute')){
if (val){
if (typeof val === 'number'){
// Do something here if val is a typeof number
}
} else {
// Do something here if val doesn't exist
}
}
}
console.log("Let me see what is value ::: ", val);
console.log("Let me see what is elem ::: ", elem);
return original_val.apply(this, [val]);
}
})(jQuery);
使用上面的代码,我检查输入元素是否具有某个属性,然后继续修改该值,然后将其传递给原始jQuery的val()方法。
使用此方法,我设法在使用以下代码时修改该值
$(id).val(10000)
但是当我尝试使用底部代码检索值时,它失败了
$(id).val()
还有一些,我修改它后,我不能再使用trim()之类的其他方法链接val()方法,因为它会抛出以下错误
Uncaught TypeError: input.val(...).trim is not a function
我在这做错了什么?
这是因为你的代码在调用它时总是为原始val
提供一个参数,即使它被用作吸气剂。所以原来的val
总是认为它被调用来设定价值。
我会让getter case从函数中提前退出,就在顶部附近:
if (!arguments.length) {
return original_val.call(this);
}
(这与jQuery的检查相同。)
一些旁注:
return original_val.apply(this, [val]);
可以更有效地编写如下:
return original_val.call(this, val);
无需创建该数组。undefined
而不是实例,请参阅***
评论:
(function($) {
var original_val = jQuery.fn.val;
jQuery.fn.val = function(value) {
// *** Early exit when used as a getter
if (!arguments.length) {
return original_val.call(this);
}
var elem = this[0],
val = undefined;
// Set for value first, if its undefined
// *** Note: This converts any falsy value to "", not just undefined.
// *** Later you have a check for `val` being a number. `0` is falsy.
val = value ? value : "";
if (elem) {
if (elem.hasAttribute('thisattribute')) {
if (val) { // *** Again, 0 is falsy
if (typeof val === 'number') {
// Do something here if val is a typeof number
}
} else {
// Do something here if val doesn't exist
}
// Just for the purposes of demonstration:
val = val.toUpperCase ? val.toUpperCase() : val;
}
}
console.log("Let me see what is value ::: ", val);
console.log("Let me see what is elem ::: ", elem);
return original_val.call(this, val);
}
})(jQuery);
// *** Setting a value
$("#txt").val("foo");
// *** Reading a value
console.log($("#txt").val());
<input type="text" id="txt" value="" thisattribute="">
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>