Writing callback functions
I'm using jQuery to write things like this:
$('#current_image').fadeOut(function(){
$('#current_image').attr('src',newImage).show();
});
This is lovely, once the fadeOut has completed, the nested bit executes.
I'd like to make my own function here that would replace fadeOut. What would my function look like so that this code would work?
$('#current_image').customFadeOut(function(){
$('#current_image').attr('src',newImage).show();
});
The key is just passing the function reference to the prototypal method you define, and binding that passed function to $.animate
or whatever jquery animation function you use internally in that.
HTML:
<div id="blah" style="color:#fff; opacity:1; background:black; height:50px; position:relative; ">fsdljfdsjfds</div>
<a id="click" href="#">fjsd</a>
JS:
$.fn.customFadeOut = function (callback) {
return $(this).animate({
opacity: 0.25,
fontSize: "3em",
height: 'toggle'
}, 5000, function () {
callback.apply(this)
});
}
$('#click').click(function () {
$('#blah').customFadeOut(function () {
alert('hi')
})
})
Live Demo
链接地址: http://www.djcxy.com/p/2800.html下一篇: 编写回调函数