2

我想将事件侦听器绑定/取消绑定到窗口大小调整我正在使用 .on()/.off() 函数来做到这一点。因为 .off() 需要传递与 .on() 相同的函数,所以我创建了一个单独的函数,该函数在两个地方都传递。

这是代码(不工作):

var i = 0;
function onResizeListener(){
    $('#debug').html(i);
    i++;
}
$(document).ready(function() {
    $(window).on('resize',onResizeListener());
});

示例:http: //jsfiddle.net/eRupC/2/

这个正在工作: http: //jsfiddle.net/eRupC/1/当我onResizeListener()用匿名函数包装时。

示例中的理想结果:当您调整窗口大小时,数字已更改。

提前致谢。

4

3 回答 3

2

Try this if you need to pass something to onResizeListener. If not, remove the parenthesis from onResizeListener as the the other answers say. Bind Documentation

$(document).ready(function() {
  var x = 2;
  var y = 4;
  $(window).bind('resize', function() {
    onResizeListener(x, y);
  });
});

This would also work:

$(document).ready(function() {
  $(window).on('resize', function() {
    onResizeListener();
  });
});

To unbind the function call from the resize event but still pass parameters to the function you could use:

$(document).ready(function() {
    //bind
    $(window).bind('resize', { foo: 'bar' },onResizeListener);

    //unbind, wrap in event you wish to use to unbind it
    $(window).unbind('click', onResizeListener);
});
于 2012-10-10T18:15:04.203 回答
0

You need to remove the brackets from the event handler code...

var i = 0;
function onResizeListener(){
    $('#debug').html(i);
    i++;
}
$(document).ready(function() {
    $(window).on('resize',onResizeListener);
});
于 2012-10-10T18:15:23.097 回答
0

替换这一行

  $(window).on('resize',onResizeListener());

有了这个

  $(window).on('resize',onResizeListener);

http://jsfiddle.net/pc5uC/

于 2012-10-10T18:21:27.347 回答