开发者

JQuery hide div - resulting in javascript error

开发者 https://www.devze.com 2022-12-16 22:04 出处:网络
I have the following html in page: <head> <script src=\"jquery-1.3.2.min.js\" type=\"text/javascript\"></script>

I have the following html in page:

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

When I click on the div, it results in 开发者_如何学Cthe following JavaScript error:

Line: 53 Error: 'this[...].style' is null or not an object

Any solutions?


There are no definition to this object in that scope. Use selectors instead:

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

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


this refers to the current object. For your code to work you have to pass a reference to the div element by passing this inside the function call.

The main advantage of using jQuery is to separate markup and script. So you won't write event handlers inside the markup. You can write event handlers only after the DOM is ready.

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

A detailed reading on Unobtrusive JavaScript


This should fix it

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

and

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


$(this) will only be your DIV if you bind the event with jQuery:

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

The way you're doing it, you need to pass a reference to the object:

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

and use that in your function:

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


Try this:

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

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

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号