JQuery hide div - resulting in javascript error
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>
精彩评论