Javascript'this'关键字返回href属性,而不是锚标记上的Object [英] Javascript 'this' keyword returning href attribute rather than Object on anchor tag

查看:100
本文介绍了Javascript'this'关键字返回href属性,而不是锚标记上的Object的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

要求:返回元素对象.
问题:使用下面的代码,我期望链接以返回[对象],但是它们实际上返回href属性中的字符串(或者在第一个链接的情况下) ,即Window对象).

Requirement: Return the element object.
Problem: Using the code below, I expected the links to return [object], but they actually return the string in the href attribute (or in the case of the first link, the Window object).

(以下HTML已在FireFox 3.6.8和Internet Explorer 7(7.0.6002.18005)中经过测试,结果相同.)

(The HTML below has been tested in FireFox 3.6.8 and Internet Explorer 7 (7.0.6002.18005) with the same results.)

<!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="">&lt;a href=&quot;javascript:alert(this);&quot;&gt;...&lt;a/&gt;</a> - Returns: [object Window]<br />
            <a href="#" onclick="alert(this);" title="">&lt;a href=&quot;#&quot; onclick=&quot;alert(this);&quot;&gt;...&lt;a/&gt;</a> - Returns: Full URI<br />
            <a href="javascript:void(0);" onclick="alert(this);" title="">&lt;a href=&quot;javascript:void(0);&quot; onclick=&quot;alert(this);&quot;&gt;...&lt;a/&gt;</a> - Returns: javascript:void(0);
        </div>
    </body>
</html>  

在此关键字中添加.tagname会为第一个链接返回undefined,但正确地将第二个和第三个链接标识为A.同样,请求.href返回第一个链接的undefined,但正确输出href(对于'#',为完整URI).

Adding .tagname to the this keyword returns undefined for the first link but correctly identifies the second and third as A. Likewise, requesting .href returns undefined for the first link but correctly outputs the href (full URI in the case of '#').

有人知道为什么吗,以及如何获得对A对象本身的控制权?

Does anyone know why, and how I can get a hold on the A object itself?

推荐答案

访问第二个和第三个链接中的属性是可行的.这意味着this确实是A DOM元素,但是当将其转换为字符串时(这就是您要alert发生的事情),它将转换为URL.

As you said, accessing a property in the second and third link works. That means that this is indeed the A DOM element but when it is converted to a string (which is what happens when you want to alert it) it is converted to the URL.

所以您已经有了对象;)

So you already have your object ;)

当您执行alert(document.location)时,也会发生同样的情况.它实际上是一个对象,但是当转换为字符串时,它将显示当前位置.

Same happens when you do alert(document.location). It is actually an object but when converted to a string, it prints the current location.

这篇关于Javascript'this'关键字返回href属性,而不是锚标记上的Object的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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