这么写,点击链接时,链接会变成粉色,并且输出 over<html>
<head>
<script type="text/javascript">
function f()
{
this.style.color = "pink";
alert("over");
}
</script>
</head>
<body>
<a href="#" id="hrf" >测试链接</a>
<script type="text/javascript">
document.getElementById("hrf").onclick = f;
</script>
</body>
</html>
可是把最后那段动态添加事件的js代码去掉,直接将事件处理写在标签上,就不能正常运行了,点击链接会报错。请问第二种写法错在哪里?
===错误代码===<html>
<head>
<script type="text/javascript">
function f()
{
this.style.color = "pink";
alert("over");
}
</script>
</head>
<body>
<a href="#" id="hrf" onclick="f();">测试链接</a>
</body>
</html>

解决方案 »

  1.   


    <html>
    <head>
        <script type="text/javascript">
            function f(obj)
            {
                obj.style.color = "pink";
                alert("over");
            }
        </script>
    </head>
    <body>
        <a href="#" id="hrf" onclick="f(this);">测试链接</a>
    </body>
    </html>第一种情况this表示a标签这个对象,这二种情况this代表window对象
      

  2.   


    <html>
    <head>
        <script type="text/javascript">
            function f(a)
            {
                a.style.color = "pink";
                alert("over");
            }
        </script>
    </head>
    <body>
        <a href="#" id="hrf" onclick="f(this);">测试链接</a>
    </body>
    </html>
    因为它找不到当前元素,你传进去一个this就成了,代表当前元素
      

  3.   

    请再讲细些吧。为什么你的例子中,在 onclick="f(this);" 中,参数this代表超链接对象,
    可是在我的错误代码中onclick="f()"方法体里的this却不代表超链接对象呢?
      

  4.   


    this代表当前对象~·也就是超链接对象~`因为你得给它传递参数~`把this传进去~·f()方法才能找到~`
      

  5.   

    this指向的是调用f()这个方法的对象。http://birdshome.cnblogs.com/archive/2005/03/07/95931.aspx
      

  6.   

    用Firefox调试,有个错误控制台能看到错误