2010-01-18 46 views
0

我在页面下面的HTML:JQuery的隐藏格 - 导致JavaScript错误

<head> 
<script src="jquery-1.3.2.min.js" type="text/javascript"></script>  
<script> 
     function hideIt() { 
      $(this).hide("slow"); 
      return true; 
     }   
    </script> 
</head> 
<body> 
<div onclick="hideIt();"> 
     hello world 
    </div> 
</body> 

当我点击的股利,它导致下面的JavaScript错误:

行:53 错误:'this [style]'为空或不是对象

任何解决方案?

+0

这是在JavaScript中共同得到这样的错误,以及解决这些问题的好方法是使用内置的调试器,或'的console.log()'在详细阅读有问题的物品。 – Anurag 2010-01-18 10:02:18

回答

0

这应该修复它

<div onclick="hideIt(this);"> 

function hideIt(o) { 
      $(o).hide("slow"); 
      return true; 
     }  
1

没有定义,在该范围this对象。 使用选择,而不是:

<div class="ready_to_hide"> 
    hello world 
</div> 

$('.ready_to_hide').click(function(){ 
    $(this).hide(); 
}); 
+0

有 - 窗口对象。 (虽然这不是一个有用的定义) – Quentin 2010-01-18 10:03:45

0

$(this)只会成为你的DIV如果你绑定使用jQuery事件:

$('#myDiv').click(hideIt); 

你这样做的方式,你需要传递给该对象的引用:

<div onclick="hideIt(this);"> 

和使用,在你的函数:

function hideIt(obj) { 
     $(obj).hide("slow"); 
     return true; 
    } 
0

试试这个:

<script> 
    function hideIt(item) { 
     $(item).hide("slow"); 
     return true; 
    }   
</script> 

<div onclick="hideIt(this);"> 
    hello world 
</div> 
1

this指当前对象。为了使代码正常工作,必须在函数调用中传递this来传递对div元素的引用。

使用jQuery的主要优点是将标记和脚本分开。所以你不会在标记中写入事件处理程序。只有在DOM准备好之后,才能编写事件处理程序。

<head> 
    <script src="jquery-1.3.2.min.js" type="text/javascript"></script>  
    <script> 
     $(function(){ 
      $("#divToHide").click(function(){ 
       $(this).hide(); 
      }); 
     });   
    </script> 
    </head> 
    <body> 
    <div id="divToHide"> 
      hello world 
     </div> 
    </body> 

Unobtrusive JavaScript