jquery:取消绑定一个加载的函数

时间:2010-09-13 16:26:30

标签: jquery resize unbind document-ready

我有一个功能,可以在加载页面时调整图像背景的大小,

$(document).ready(function(){
loadBackground();
});

我想点击按钮时“卸载”或“删除”此加载的函数,以便我可以重新加载此函数,而不是将其加载到页面顶部,

$('.get-image').click(function(){
        $(window).unbind("resize",loadBackground);
        loadBackground();
 return false;
 });

但我不能让它发挥作用!有什么想法吗?

感谢, 刘

1 个答案:

答案 0 :(得分:0)

根据你的评论,我认为你根本不需要解开:

您首先要在加载页面时加载背景,然后在点击发生时加载背景。

调整图像大小时背景会发生什么应该是绑定到$(window).resize()的另一个单独的函数...所以整个事情看起来像这样:

$(function() { ... });$(document).ready(function() { ... })相同,只是写得更快:

$(function() { 
      // Define load BG
    function loadBackground() {
        /// ...
    }

      // Define what happens to the BG image on resize
      // this doesn't have to change. It should refer
      // to the generic `background-image`
    $(window).resize(function() { 
        // ...
    });

      // load BG when page is ready:
    loadBackground();

      // load another BG if there's a click:
      // This will effectively cancel the previous load bg
    $('.get-image').click(function() { 
        loadBackground();
        return false;
    });    
});

// I'm assuming you're somehow changing which BG image is loaded
// something like loadBackground(image)... and you could initially 
// load a default image, and then, if there's a click, you could
// determine what image should be based on what was clicked.