传递“这个”进入 $.trim() 函数
Jquery in Action 具有以下代码:
$('#someField').val($.trim($('#someField').val()));
但是,当我按如下方式重写时,该代码不起作用。
$('#someField').val($.trim($(this));
谁能帮助我理解为什么这不起作用?
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 anyone help me understand why this does not work?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
有两个原因:
trim
采用字符串,而不是 jQuery 对象。您至少需要$(this).val()
。选择器没有封装函数,因此
this
实际上没有设置为您选择的对象。this
无论如何都是如此。最好的解决方案是这样的:
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:
$.trim
期望接收一个字符串作为参数。$(this)
不是字符串。$.trim
expects to receive a string as an argument.$(this)
is not a string.$('#someField').val()
检索某个字段的文本,因此 trim 的工作方式与处理字符串相同。$(this)
只是一个 jQuery 对象(this
指的是调用它的上下文),因此trim
没有任何意义。$('#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), hencetrim
has no meaning on it.您需要在另一个函数中才能更改 this 关键字。例如:
当然,上一个示例中的
this
更改为我们动画的对象是 jQuery 为我们所做的事情,它不是自动的。虽然这样的事情是可能起作用的:jQuery 选择不让您将函数作为参数传递给
.val()
方法,因为它通常不会以这种方式使用,因此什么你正在尝试是行不通的。编辑:
现在我想了一下,实现起来并不难:
<保罗·爱尔兰的《打鸭子》(读它!)
You need to be in another function for the this keyword to change. For example:
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: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:
Duck Punching by Paul Irish (read it!)
当您执行该代码时,
this
引用您所在函数的所有者。那么,
$(this)
将永远不会解析为文本,其中$('#someField').val()
会的。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.当 $.trim 被点击时,
this
不再是#someField
元素,而是DOMWindow
。这是因为$
驻留在DOMWindow
中,而不是您的#someField
元素中When $.trim is hit,
this
is no longer the#someField
element but rather, theDOMWindow
. This is because$
resides in theDOMWindow
and not your#someField
element