jQuery按钮单击“此" [英] jQuery Button Click 'this'
问题描述
假设我们有一个简单的事件按钮处理程序:
Say we have a simple event button handler:
$( "#aButton" ).click(function() {
console.log( "tile" + this.val() + "clicked" );
});
我意识到"this"是大多数上下文,它将引用"window"对象.....但是我到处都在查看"this"的代码示例时,都谈到了Jquery是一种特殊情况,其中this
是基于所谓的函数",而窗口"是所谓的函数?
I realize that "this" is most contexts would refer to the "window" object.....but everywhere i've been looking at code examples of "this" talks about Jquery being a special case, where this
is implied to be whatever object the event handler was on (Which i've always thought this
was based on whatever "called" the function, and the "Window" is what called the function?
如果这根本不适用于jQuery,是否有更好的方法来引用被单击的对象?
If this simply isn't true for jQuery, is there a better way around referring to the object that was clicked on?
推荐答案
使用$(this)
获取被单击的元素.
Use $(this)
to obtain the clicked element.
$("#aButton").click(function() {
console.log("tile " + $(this).val() + " clicked");
});
此外,您可以注意到$(this)[0] === this
this
.在这种情况下使用this
将返回触发事件的节点.
this
should can be used when using built in JavaScript methods, such as .addEventListener()
. Using this
in this context will return the Node that triggered the event.
这篇关于jQuery按钮单击“此"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!