Javascript / jQuery:为什么使用< a>标签console.log中的其他元素,alert()与$(this)在一起 [英] Javascript/jQuery: Why different result for event.target using <a> tag Vs. other Elements in console.log, alert() with $(this) in mind
问题描述
在使用event.log处理DOM时,似乎有一些值得理解的东西。
将警报中的结果与firebug中的console.log进行比较。 >
我有这个代码HTML:
< div>点击我< Div>< / div>
< a href =#>点击我< a>< / a>
和JS:
$(function(){
/ pre>
$('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))
})
})
当Div或被点击时:
console.log
两个工作的预期
但是
警报
显示不同的输出: / p>
对于DIV:
1 objectHTMLDivElement
2对象对象//使用jQuery的$(this)
但是, code>< a> 标记被点击它得到:
1网址或
href
属性的值
2 object Object
//使用jQuery的$(this)
为什么会这样?为什么
< a>
的警报不会将此标签打印为HTMLElement?
请在此测试:
http ://jsfiddle.net/hWR53/1/解决方案所有对象,其中元素包含 a
toString
函数,并且该对象上调用此toString
函数来构建警报中显示的内容。
对于大多数对象,此函数返回
[object Object]
,但a
元素的实例具有被覆盖以返回元素的href
属性的值。There seems to be something worth understanding when handling DOM using event.log.
Comparing the results in an alert and the console.log in firebug.
I have this Code HTML:
<div>Click Me < Div ></div> <a href="#">Click Me < a ></a>
and 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:
The
console.log
of both work as expectBut the
alert
s show up with different outputs:For DIV:
1 objectHTMLDivElement
2 object Object//using jQuery's $(this)
However, when the
<a>
tag is Clicked it yields:1 The web address or the
href
attribute's value2 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?Please test for yourself here: http://jsfiddle.net/hWR53/1/
解决方案All objects, among them elements, have a
toString
function, and thistoString
function is called on the object to build what is displayed in the alert.For most objects, this function returns
"[object Object]"
but instances ofa
elements have it overridden to return the value of thehref
property of the element.这篇关于Javascript / jQuery:为什么使用< a>标签console.log中的其他元素,alert()与$(this)在一起的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!