jquery on() 数据参数 - $(this) 指整个文档
使用jquery时,我经常在事件、函数等中使用$(this)
。
最近我尝试了以下操作:
function btn_edit_click (event) {
alert(event.data.idnum);
}
$(".btn_edit").on("click", { idnum: $(this).attr("title") }, btn_edit_click);
出于某种原因,我获得了整个页面的标题,而不是元素(s) 由 $(".btn_edit")
引用。我做错了什么,还是这是预期的行为?
When using jquery, I have frequently made use of $(this)
within events, functions, etc.
Recently I tried the following:
function btn_edit_click (event) {
alert(event.data.idnum);
}
$(".btn_edit").on("click", { idnum: $(this).attr("title") }, btn_edit_click);
For some reason I get the title of the entire PAGE, rather than the element(s) being referenced by $(".btn_edit")
. Am I doing something wrong, or is this expected behaviour?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
这取决于这段代码嵌套在什么内容中。如果答案是什么,则
this
引用window
对象。如果您在事件处理程序中引用
this
,则this
将引用触发事件的元素。但看起来好像您在全局空间中使用this
。如果您希望在回调函数中可以访问
.btn_edit
元素的标题,只需在回调函数中引用this
(请注意它如何简化了您的代码):这是一个演示: http://jsfiddle.net/gRK3z/
这里还有一个性能测试来展示使用之间的区别
.attr('title')
和.title
: http://jsperf.com/jquery-attr-title-vs-titleWell it depends what this code is nested within. If the answer is nothing then
this
refers to thewindow
object.If you were referring to
this
inside an event handler thenthis
would refer to the element on which the event triggered. But it appears as though you are usingthis
in the global space.If you want the title of the
.btn_edit
element to be accessible in the callback function just refer tothis
in your callback function (notice how it simplifies your code as well):Here is a demo: http://jsfiddle.net/gRK3z/
Also here is a performance test to show the difference between using
.attr('title')
and.title
: http://jsperf.com/jquery-attr-title-vs-title$(this)
是在全局范围内调用的,而不是在回调方法内调用。所以是的,您应该期望使用$(this)
取回窗口或文档对象。更好的解决方案可能是:
$(this)
is being called within the global scope here, not within a callback method. So yes, you should expect to get the window or document object back with$(this)
.A better solution might be:
正如其他人指出的那样,
this
的上下文并不是您期望的那样。我认为这是一种更简单、更易读的方式来完成您想要做的事情:The context of
this
is not what you expect it to be, as others have pointed out. I think this is a less convoluted and more readable way of doing what it is you are trying to do:在您的情况下,您将一个对象传递给
on
函数,因此this
是您所在范围内的任何内容。除非设置,否则
this 通常设置为
window
。In your case you are passing an object to the
on
function, sothis
is whatever it is in the scope you're in.Unless set,
this
is usually set towindow
.当您创建一个对象来传递数据时,它不在选择器的范围内。相反,您可以简单地传递要在处理程序中执行的函数的名称。
然后,函数中的
this
将与选择器中指定的元素相关联,从而无需首先传递对象:小提琴示例
As you are creating an object to pass data across it is not in the scope of the selector. Instead you could simply pass the name of your function to be executed in the handler.
this
in your function would then relate to the element as specified in your selector, saving the need for you to pass the object in the first place:Example fiddle