[英]Javascript/jQuery: Why different result for event.target using <a> tag Vs. other Elements in console.log, alert() with $(this) in mind
There seems to be something worth understanding when handling DOM using event.log. 使用event.log处理DOM时似乎有些事情值得理解。
Comparing the results in an alert and the console.log in firebug. 比较警报中的结果和firebug中的console.log。
I have this Code HTML: 我有以下代码HTML:
<div>Click Me < Div ></div>
<a href="#">Click Me < a ></a>
and JS: 和JS:
$(function(){
$('div').click(function(e){
console.log(e.target);
console.log($(this));
alert(e.target)
alert($(this))
})
$('a').click(function(e){
e.preventDefault();
console.log(e.target);
console.log($(this));
alert(e.target)
alert($(this))
})
})
When the Div or is Clicked: 单击Div或时:
The console.log
of both work as expect 两者的
console.log
都按预期工作
But the alert
s show up with different outputs: 但是
alert
显示为不同的输出:
For DIV: 对于DIV:
1 objectHTMLDivElement
1个对象HTMLDivElement
2 object Object//using jQuery's $(this)
2 object Object
//using jQuery's $(this)
However, when the <a>
tag is Clicked it yields: 但是,单击
<a>
标记时,将产生:
1 The web address or the
href
attribute's value1网址或
href
属性的值2 object Object
//using jQuery's $(this)
2 object Object
//using jQuery's $(this)
Why is this the case? 为什么会这样呢? Why doesn't the alert of
<a>
print this tag as being the HTMLElement? 为什么
<a>
的警报不将此标签打印为HTMLElement?
Please test for yourself here: http://jsfiddle.net/hWR53/1/ 请在此处进行自我测试: http : //jsfiddle.net/hWR53/1/
All objects, among them elements, have a toString
function , and this toString
function is called on the object to build what is displayed in the alert. 所有对象(包括元素)都具有
toString
函数 ,并且在对象上调用此toString
函数以构建警报中显示的内容。
For most objects, this function returns "[object Object]"
but instances of a
elements have it overridden to return the value of the href
property of the element. 对于大多数目的,该函数将返回
"[object Object]"
,但实例a
元件具有它重写返回的值href
元素的属性。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.