Javascript/jQuery:为什么event.target使用<a>标记console.log,al

Javascript/jQuery: Why different result for event.target using <a> tag Vs. other Elements in console.log, alert() with $(this) in mind

本文关键字:标记 gt console log al lt 为什么 event target Javascript 使用      更新时间:2023-09-26

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

比较firebug中的alert和console.log中的结果。

我有这个代码HTML:

<div>Click Me < Div ></div>
<a href="#">Click Me < 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))
    })
})

点击潜水器时:

两者的console.log均按预期工作

但是alert显示出不同的输出:

对于DIV:

1对象HTMLDivElement
2对象对象//using jQuery's $(this)

然而,当点击<a>标签时,它会产生:

1网址或href属性的值

2对象对象//using jQuery's $(this)

为什么会出现这种情况?为什么<a>的警报不将此标记打印为HTMLElement?

请在此处进行自我测试:http://jsfiddle.net/hWR53/1/

所有对象,包括元素,都有一个toString函数,该toString函数在对象上调用以构建警报中显示的内容。

对于大多数对象,此函数返回"[object Object]",但a元素的实例会覆盖它以返回元素的href属性的值。