在使用 event.log 处理 DOM 时,似乎有一些值得理解的东西。
比较 alert 中的结果和 firebug 中的 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))
})
})
当 Div 或被点击时:
console.log
两者都按预期工作
但是 alert
s 出现不同的输出:
对于 DIV:
1 objectHTMLDivElement
2 object Object//using jQuery's $(this)
但是,当 <a>
标签被点击它产生:
1 The web address or the
href
attribute's value2 object Object
//using jQuery's $(this)
为什么会这样?为什么<a>
的警报没有将此标记打印为 HTMLElement?
请自行测试: http://jsfiddle.net/hWR53/1/
最佳答案
所有对象,包括元素,都有a toString
function ,还有这个 toString
在对象上调用函数以构建警报中显示的内容。
对于大多数对象,此函数返回 "[object Object]"
但是 a
的实例元素将其覆盖以返回 href
的值元素的属性。
关于Javascript/jQuery : Why different result for event. 目标使用 <a> 标签对比。 console.log 中的其他元素,注意 $(this) 的 alert(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18561700/