animate in jquery not firing
my intention is to hide a div element as soon as the hide button is clicked. But the browser stays silent when i clicked the hide button.
Here is my code
$.fn.slideFadeToggle = function(easing, callback) { return this.animate({ opacity: 'toggle', height: 'toggle' }, "slow", easing, callback); }; $("#hid").click(function(){ alert('here'); $("#result").slideFadeToggle(); });
hid is the id of the button which on clicked should actually hide the div开发者_StackOverflow中文版. The alert inside the click funtction doesnt work either.
result is the id of the div to be hidden. any ideas?
The alert inside the click funtction doesnt work either.
That suggests that at the time you're doing your $("#hid").click(...
, the element with the ID hid
doesn't yet exist in the DOM. You can't access DOM elements until they're created.
Three ways to make sure they've been created before you try to access them are to use the jQuery ready
function, to simply ensure that your script code is loaded after the element in question, or to use jQuery's live
feature.
So for instance, this will fail:
<html>
...
<script type='text/javascript' src='jquery.js'></script>
<script type='text/javascript'>
$("#hid").click(...);
</script>
</head>
<body>
<div id='hid'>...</div>
...
But this will work (via a shortcut for ready
):
<html>
...
<script type='text/javascript' src='jquery.js'></script>
<script type='text/javascript'>
jQuery(function($) {
$("#hid").click(...);
});
</script>
</head>
<body>
<div id='hid'>...</div>
...
As will this (because the script is located after the element in the markup):
<html>
...
<script type='text/javascript' src='jquery.js'></script>
</head>
<body>
<div id='hid'>...</div>
<script type='text/javascript'>
$("#hid").click(...);
</script>
...
...that latter being the way the Google team behind Closure recommend; similarly, the YUI team recommend putting your scripts just before your closing body
tag, which comes to the same thing.
And this will work (via live
):
<html>
...
<script type='text/javascript' src='jquery.js'></script>
<script type='text/javascript'>
$("#hid").live('click', ...);
</script>
</head>
<body>
<div id='hid'>...</div>
...
Well, it works for me in chrome : jsfiddle
Do you import jquery before that code ?
精彩评论