Passing "this" into the $.trim() function
Jquery in Action has the following code:
$('#someField').val($.trim($('#someField').val()));
When I rewrite as follows though, the code does not work.
$('#someField').val($.trim($(this));
Can anyo开发者_开发问答ne help me understand why this does not work?
Two reasons:
trim
takes a string, not a jQuery object. You'd need$(this).val()
at least.The selector is not encapsulating a function, so
this
actually doesn't get set to the object you selected.this
is whatever it was anyway.
The best solution is this:
var $obj = $('#someField');
$obj.val($.trim($obj.val()); // trim object's value
$.trim
expects to receive a string as an argument. $(this)
is not a string.
$('#someField').val()
retrieves the text of somefield, hence trim works as it is working on a string.
$(this)
is just a jQuery object (this
referring to the context in which it is called), hence trim
has no meaning on it.
You need to be in another function for the this keyword to change. For example:
$('div').slideToggle(1000, function() { // notice the function keyword
// Now the this keyword has changed, notice the indentation due to the function
$(this).css('border', '1px solid black'); // Here's how we use this
});
Of course the fact that this
in the previous example changed to the object that we animated was something that jQuery did for us, it's not automatic. While it is possible for something like this to work:
$('#someField').val(function() { $.trim($(this).val()); } );
jQuery chooses not to let you pass a function as a parameter to the .val()
method since it won't normally be used that way and therefore what you're trying doesn't work.
EDIT:
Now that I think about it, it wouldn't be to hard to implement:
var _val = $.fn.val;
$.fn.val = function(a) {
return (!a || typeof a === 'string') ?
_val.call(a) :
_val.call(this, a.call( this.val() ));
}
Duck Punching by Paul Irish (read it!)
When you execute that code, this
refers to the owner of whatever function you're in.
$(this)
, then, will never resolve to text, where $('#someField').val()
will.
When $.trim is hit, this
is no longer the #someField
element but rather, the DOMWindow
. This is because $
resides in the DOMWindow
and not your #someField
element
精彩评论