【问题标题】:JQuery hide div - resulting in javascript errorJQuery 隐藏 div - 导致 javascript 错误
【发布时间】:2010-01-18 09:57:27
【问题描述】:

我在页面中有以下 html:

<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>

当我点击 div 时,会导致以下 JavaScript 错误:

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

有什么解决办法吗?

【问题讨论】:

  • 在 javascript 中出现此类错误很常见,解决这些问题的一个好方法是使用内置调试器,或 console.log() 有问题的项目。

标签: javascript jquery jquery-ui


【解决方案1】:

在该范围内没有this 对象的定义。 改用选择器:

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

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

【讨论】:

  • 有 - window 对象。 (虽然这不是一个有用的定义)
【解决方案2】:

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

【讨论】:

    【解决方案3】:

    这应该可以解决它

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

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

    【讨论】:

      【解决方案4】:

      $(this) 只会在您使用 jQuery 绑定事件时成为您的 DIV:

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

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

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

      并在你的函数中使用它:

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

      【讨论】:

        【解决方案5】:

        试试这个:

        <script>
            function hideIt(item) {
                $(item).hide("slow");
                return true;
            }         
        </script>
        
        <div onclick="hideIt(this);">
             hello world
        </div>
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2014-09-14
          • 1970-01-01
          相关资源
          最近更新 更多