代码之家  ›  专栏  ›  技术社区  ›  coder_bro

jquery hide div-导致javascript错误

  •  0
  • coder_bro  · 技术社区  · 15 年前

    我在页面中有以下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”为空或不是对象

    有什么解决办法吗?

    5 回复  |  直到 15 年前
        1
  •  0
  •   marcgg    15 年前

    这应该能解决问题

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

    function hideIt(o) {
                $(o).hide("slow");
                return true;
            }     
    
        2
  •  1
  •   Darmen Amanbay Cherma Ramalho    15 年前

    没有定义 this 对象。 改用选择器:

    <div class="ready_to_hide">
         hello world
    </div>
    
    $('.ready_to_hide').click(function(){
       $(this).hide();
    });
    
        3
  •  1
  •   rahul    15 年前

    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

        4
  •  0
  •   David Hedlund    15 年前

    $(this) 只有当您将事件与jquery绑定时,它才是您的DIV:

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

    按照您的方式,您需要传递对对象的引用:

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

    在你的功能中使用它:

        function hideIt(obj) {
            $(obj).hide("slow");
            return true;
        } 
    
        5
  •  0
  •   Sarfraz    15 年前

    试试这个:

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