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

查看:148
本文介绍了Javascript / jQuery:为什么使用< a>标签console.log中的其他元素,alert()与$(this)在一起的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在使用event.log处理DOM时,似乎有一些值得理解的东西。



将警报中的结果与firebug中的console.log进行比较。 >

我有这个代码HTML:

 < div>点击我< Div>< / div> 
< a href =#>点击我< a>< / a>

和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))
})
})
/ pre>

当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 expect

But the alerts 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 value

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?

Please test for yourself here: 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.

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.

这篇关于Javascript / jQuery:为什么使用&lt; a&gt;标签console.log中的其他元素,alert()与$(this)在一起的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆