要求:返回元素对象 问题:使用下面的代码,我期望返回[object]的链接,但它们实际上返回了href属性中的字符串(或者在第一个链接的情况下) ,Window对象)。
(下面的HTML已经在FireFox 3.6.8和Internet Explorer 7(7.0.6002.18005)中测试过,效果相同。)
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Anchor onclick tests</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
</head>
<body>
<div>
<a href="javascript:alert(this);" title=""><a href="javascript:alert(this);">...<a/></a> - Returns: [object Window]<br />
<a href="#" onclick="alert(this);" title=""><a href="#" onclick="alert(this);">...<a/></a> - Returns: Full URI<br />
<a href="javascript:void(0);" onclick="alert(this);" title=""><a href="javascript:void(0);" onclick="alert(this);">...<a/></a> - Returns: javascript:void(0);
</div>
</body>
</html>
向this关键字添加.tagname
会为第一个链接返回undefined
,但会正确地将第二个和第三个标识为A
。同样,请求.href
为第一个链接返回undefined
但正确输出href(在'#'的情况下为完整URI)。
有谁知道为什么,以及如何抓住A
对象本身?
答案 0 :(得分:6)
正如您所说,访问第二个和第三个链接中的属性有效。这意味着this
确实是A
DOM元素,但是当它被转换为字符串时(当你想要alert
时会发生这种情况),它会被转换为URL。 / p>
所以你已经拥有了你的对象;)
执行alert(document.location)
时也会发生同样的情况。它实际上是一个对象,但当转换为字符串时,它会打印当前位置。
答案 1 :(得分:1)
当调用alert
时,会在内部调用toString
方法,因此对于警告href的锚点的情况,锚点的toString会返回href。
<a id="foo" href="blah">fsdjl</a>
在JS控制台中,执行:
document.getElementById('foo').toString()
这将证实它。
对于window
,this
未绑定到锚所拥有的方法,因此this
指的是全局上下文。 onclick
绑定到锚点,因此this
(即当前执行上下文)将更改为锚点。
<a href="#" onclick="javascript:alert( this.nodeName )">blah</a>
结果是警告A
这是nodeName,因此如果设置了href
,浏览器会返回href
,因此它更“可读”且不那么模糊。 / p>