jQuery $(this) 和 event.target 的区别?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12077859/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Difference between $(this) and event.target?
提问by Rafael Adel
I'm new to jQuery, and was making tabbed panels, following the tutorial in JavaScript and jQuery : The Missing Manual, there's that first line when the author does this :
我是 jQuery 的新手,正在制作选项卡式面板,按照JavaScript 和 jQuery 中的教程:The Missing Manual,当作者这样做时,有第一行:
var target = $(this);
But i tried to do it that way
但我试着那样做
var target = evt.target;
and i got that error :
我得到了那个错误:
Uncaught TypeError: Object http://localhost/tabbedPanels/#panel1 has no method 'attr'
And when i changed evt.target
back to $(this)
, it worked like a charm.
当我改evt.target
回 时$(this)
,它就像一个魅力。
I want to know what's the difference between $(this)
and evt.target
?
我想知道什么是之间的区别$(this)
和evt.target
?
Here's my code in case you needed it :
这是我的代码,以防您需要它:
index.html :
索引.html:
<!DOCTYPE html>
<html>
<head>
<title>Tabbed Panel</title>
<style>
body {
width : 100%;
height: 100%;
}
#wrapper {
margin : auto;
width : 800px;
}
#tabsContainer {
overflow: hidden;
}
#tabs {
padding:0;
margin:0;
}
#tabs li {
float : left;
list-style:none;
}
#tabs a {
text-decoration:none;
padding : 3px 5px;
display : block;
}
#tabs a.active {
background-color : grey;
}
#panelsContainer {
clear: left;
}
#panel1 {
color : blue;
}
#panel2 {
color : yellow;
}
#panel3 {
color: green;
}
#panel4 {
color : black;
}
</style>
<script type="text/javascript" src="jquery-1.8.0.min.js"></script>
<script type="text/javascript" src="script.js"></script>
</head>
<body>
<div id="wrapper">
<div id="tabsContainer">
<ul id="tabs">
<li><a href="#panel1">Panel1</a></li>
<li><a href="#panel2">Panel2</a></li>
<li><a href="#panel3">Panel3</a></li>
<li><a href="#panel4">Panel4</a></li>
</ul>
</div>
<div id="panelsContainer">
<div id="panel1" class="panel">
this is panel1
</div>
<div id="panel2" class="panel">
this is panel2
</div>
<div id="panel3" class="panel">
this is panel3
</div>
<div id="panel4" class="panel">
this is panel4
</div>
</div>
</div>
</body>
</html>
script.js :
脚本.js:
$(function(){
$("#tabs a").click(function(evt){
var target = evt.target,
targetPanel = target.attr("href");
$(".panel").hide();
$("#tabs a.active").removeClass("active");
target.addClass("active").blur();
$(targetPanel).fadeIn(300);
evt.preventDefault();
});
$("#tabs a:first").click();
})
回答by Petr Bela
There isa difference between $(this)
and event.target
, and quite a significant one. While this
(or event.currentTarget
, see below) always refers to the DOM element the listener was attached to, event.target
is the actual DOM element that was clicked. Remember that due to event bubbling, if you have
有是之间的差异$(this)
,并event.target
和相当显著之一。虽然this
(或event.currentTarget
,见下文)总是指侦听器附加到event.target
的 DOM 元素,是被点击的实际 DOM 元素。请记住,由于事件冒泡,如果您有
<div class="outer">
<div class="inner"></div>
</div>
and attach click listener to the outer div
并将单击侦听器附加到外部 div
$('.outer').click( handler );
then the handler
will be invoked when you click inside the outer div as well as the inner one (unless you have other code that handles the event on the inner div and stops propagation).
然后handler
当您在外部 div 和内部 div 内部单击时将调用 div(除非您有其他代码处理内部 div 上的事件并停止传播)。
In this example, when you click inside the inner div, then in the handler
:
在本例中,当您在内部 div 内部单击时,然后在handler
:
this
refers to the.outer
DOM element (because that's the object to which the handler was attached)event.currentTarget
also refers to the.outer
element (because that's the current targetelement handling the event)event.target
refers to the.inner
element (this gives you the element where the event originated)
this
指的是.outer
DOM 元素(因为它是处理程序附加到的对象)event.currentTarget
也指.outer
元素(因为这是处理事件的当前目标元素)event.target
指的是.inner
元素(这为您提供了事件起源的元素)
The jQuery wrapper $(this)
only wraps the DOM element in a jQuery object so you can call jQuery functions on it. You can do the same with $(event.target)
.
jQuery 包装器$(this)
仅将 DOM 元素包装在 jQuery 对象中,以便您可以在其上调用 jQuery 函数。您可以对$(event.target)
.
Also note that if you rebind the context of this
(e.g. if you use Backbone it's done automatically), it will point to something else. You can always get the actual DOM element from event.currentTarget
.
另请注意,如果您重新绑定的上下文this
(例如,如果您使用 Backbone,它会自动完成),它将指向其他内容。您始终可以从event.currentTarget
.
回答by nbrooks
this
is a reference for the DOM element for which the event is being handled (the current target). event.target
refers to the element which initiated the event. They were the same in this case, and can often be, but they aren't necessarily always so.
this
是对其处理事件的 DOM 元素(当前目标)的引用。event.target
指的是发起事件的元素。在这种情况下,它们是相同的,并且通常可以是,但它们不一定总是如此。
You can get a good sense of this by reviewing the jQuery event docs, but in summary:
通过查看jQuery 事件文档,您可以很好地了解这一点,但总而言之:
event.currentTarget
The current DOM element within the event bubbling phase.
event.delegateTarget
The element where the currently-called jQuery event handler was attached.
event.relatedTarget
The other DOM element involved in the event, if any.
event.target
The DOM element that initiated the event.
事件.currentTarget
事件冒泡阶段中的当前 DOM 元素。
event.delegateTarget
附加当前调用的 jQuery 事件处理程序的元素。
事件相关目标
事件中涉及的其他 DOM 元素(如果有)。
事件目标
发起事件的 DOM 元素。
To get the desired functionality using jQuery, you must wrap it in a jQuery object using either: $(this)
or $(evt.target)
.
要使用 jQuery 获得所需的功能,您必须使用以下任一方法将其包装在 jQuery 对象中:$(this)
或$(evt.target)
。
The .attr()
method only works on a jQuery object, not on a DOM element. $(evt.target).attr('href')
or simply evt.target.href
will give you what you want.
该.attr()
方法仅适用于 jQuery 对象,不适用于 DOM 元素。$(evt.target).attr('href')
或者干脆evt.target.href
给你你想要的。
回答by natureshop
There is a significant different in how jQuery handles the this variable with a "on" method
jQuery 使用“on”方法处理 this 变量的方式有很大不同
$("outer DOM element").on('click',"inner DOM element",function(){
$(this) // refers to the "inner DOM element"
})
If you compare this with :-
如果您将其与:-
$("outer DOM element").click(function(){
$(this) // refers to the "outer DOM element"
})
回答by Jaskey
http://api.jquery.com/on/states:
When jQuery calls a handler, the
this
keyword is a reference to the element where the event is being delivered; for directly bound eventsthis
is the element where the event was attached and for delegated eventsthis
is an element matching selector. (Note thatthis
may not be equal toevent.target
if the event has bubbled from a descendant element.)To create a jQuery object from the element so that it can be used with jQuery methods, use $( this ).
当 jQuery 调用处理程序时,
this
关键字是对传递事件的元素的引用;对于直接绑定事件this
是附加事件this
的元素,对于委托事件是元素匹配选择器。(请注意,如果事件从后代元素冒泡,则this
可能不等于event.target
。)要从元素创建一个 jQuery 对象以便它可以与 jQuery 方法一起使用,请使用 $( this )。
If we have
如果我们有
<input type="button" class="btn" value ="btn1">
<input type="button" class="btn" value ="btn2">
<input type="button" class="btn" value ="btn3">
<div id="outer">
<input type="button" value ="OuterB" id ="OuterB">
<div id="inner">
<input type="button" class="btn" value ="InnerB" id ="InnerB">
</div>
</div>
Check the below output:
检查以下输出:
<script>
$(function(){
$(".btn").on("click",function(event){
console.log($(this));
console.log($(event.currentTarget));
console.log($(event.target));
});
$("#outer").on("click",function(event){
console.log($(this));
console.log($(event.currentTarget));
console.log($(event.target));
})
})
</script>
Note that I use $
to wrap the dom element in order to create a jQuery object, which is how we always do.
请注意,我使用$
包装 dom 元素以创建一个 jQuery 对象,这也是我们一贯的做法。
You would find that for the first case, this
,event.currentTarget
,event.target
are all referenced to the same element.
您会发现对于第一种情况,this
、event.currentTarget
、event.target
都引用了同一个元素。
While in the second case, when the event delegate to some wrapped element are triggered, event.target
would be referenced to the triggered element, while this
and event.currentTarget
are referenced to where the event is delivered.
而在第二种情况下,当某个包装元素的事件委托被触发时,event.target
将引用被触发的元素,而this
和event.currentTarget
则引用事件的传递位置。
For this
and event.currentTarget
, they are exactly the same thing according to http://api.jquery.com/event.currenttarget/
对于this
和event.currentTarget
,根据http://api.jquery.com/event.currenttarget/,它们完全相同
回答by Beetroot-Beetroot
There are cross browser issues here.
这里存在跨浏览器问题。
A typical non-jQuery event handler would be something like this :
一个典型的非 jQuery 事件处理程序是这样的:
function doSomething(evt) {
evt = evt || window.event;
var target = evt.target || evt.srcElement;
if (target.nodeType == 3) // defeat Safari bug
target = target.parentNode;
//do stuff here
}
jQuery normalises evt
and makes the target available as this
in event handlers, so a typical jQuery event handler would be something like this :
jQuery 标准化evt
并使目标this
在事件处理程序中可用,因此典型的 jQuery 事件处理程序将是这样的:
function doSomething(evt) {
var $target = $(this);
//do stuff here
}
A hybrid event handler which uses jQuery's normalised evt
and a POJS target would be something like this :
使用 jQuery 规范化evt
和 POJS 目标的混合事件处理程序将是这样的:
function doSomething(evt) {
var target = evt.target || evt.srcElement;
if (target.nodeType == 3) // defeat Safari bug
target = target.parentNode;
//do stuff here
}
回答by MMKarami
Within an event handler function or object method, one way to access the properties of "the containing element" is to use the special this keyword. The this keyword represents the owner of the function or method currently being processed. So:
在事件处理函数或对象方法中,访问“包含元素”的属性的一种方法是使用特殊的 this 关键字。this 关键字表示当前正在处理的函数或方法的所有者。所以:
For a global function, this represents the window.
For an object method, this represents the object instance.
And in an event handler, this represents the element that received the event.
对于全局函数,这代表窗口。
对于对象方法,这表示对象实例。
在事件处理程序中, this 代表接收事件的元素。
For example:
例如:
<!DOCTYPE html>
<html>
<head>
<script>
function mouseDown() {
alert(this);
}
</script>
</head>
<body>
<p onmouseup="mouseDown();alert(this);">Hi</p>
</body>
</html>
The content of alert windows after rendering this html respectively are:
分别渲染此html后的alert窗口内容为:
object Window
object HTMLParagraphElement
An Event object is associated with all events. It has properties that provide information "about the event", such as the location of a mouse click in the web page.
Event 对象与所有事件相关联。它具有提供“有关事件”信息的属性,例如鼠标在网页中单击的位置。
For example:
例如:
<!DOCTYPE html>
<html>
<head>
<script>
function mouseDown(event) {
var theEvent = event ? event : window.event;
var locString = "X = " + theEvent.screenX + " Y = " + theEvent.screenY;
alert(event);
alert(locString);
}
</script>
</head>
<body>
<p onmouseup="mouseDown(event);">Hi</p>
</body>
</html>
The content of alert windows after rendering this html respectively are:
分别渲染此html后的alert窗口内容为:
object MouseEvent
X = 982 Y = 329