为什么绑定和解除绑定不能按预期工作

时间:2012-10-02 14:40:51

标签: jquery

我原本是这样做的:

$('div.ocontainer').each(function() {
    var o = $(this);
    var newCode = $(this).attr('id');
    if (o.parents('.ocontainer').length != 0) {
        var oldCode = o.parents('.ocontainer').attr('id');
        console.log('unbinding '+oldCode);
        $('#'+oldCode+' a').each(function() {
            $(this).unbind('click')
            })
    }
    console.log('binding '+newCode);
    $('#'+newCode+' a').each(function() {
        $(this).click(function() {
            decideStMethod(newCode);
        })
    })
})

...但unbind无效。我最终在click函数中传递了原始代码。所以我改为使用名称间隔事件:

$('div.ocontainer').each(function() {
    var o = $(this);
    var newCode = $(this).attr('id');
    if (o.parents('.ocontainer').length != 0) {
        var oldCode = o.parents('.ocontainer').attr('id');
        console.log('unbinding '+oldCode);
        $('#'+oldCode+' a').each(function() {
            $(this).unbind('click.'+oldCode)
            })
    }
    console.log('binding click.'+newCode);
    $('#'+newCode+' a').each(function() {
        $(this).bind('click.'+newCode,function() {
            decideStMethod(newCode);
        })
    })
})

...现在unbind有效但后续的bind没有。但请注意,bind行的行如果不是后续行,则会起作用,也就是说,如果unbind之前没有行。{/ p>

使用这个是首先处理页面的一个区域,并在其中的链接上完成绑定。然后,处理子区域,如果其中一个具有自己的代码,则区域的处理程序必须是未绑定的,并用子区域替换。所有这一切的原因是子区域被动态地放置在该区域中,因此它们将是事先不知道的。哦,以防万一,这是jQuery 1.72

所以:

<div id="region" class="ocontainer">
   <div id="subregion" class="ocontainer">
      <a>

在处理区域时,链接绑定到click.region和传递'region'的函数。然后,click.region应该是未绑定的,它就是这样,并且click.subregion绑定在一个传递'subregion'的函数的位置,这不会发生。

1 个答案:

答案 0 :(得分:0)

首先,bind()unbind()是不推荐使用的功能。请改用.on().off()

这是一个有一些改进的例子。

$('div.ocontainer').each(function() {
    var o = $(this);
    var newCode = o.attr('id'); //Use cached version instead
    if (o.parents('.ocontainer').length != 0) {
        var oldCode = o.parents('.ocontainer').attr('id');
        console.log('unbinding '+oldCode);
        $('#'+oldCode+' a').each(function() {
            o.off('click', "#"+oldCode); //Turn off the event handler
        })
    }
    console.log('binding click.'+newCode);
    $('#'+newCode+' a').each(function() {
        $(this).on('click', "#" + newCode, function() {
            decideStMethod(newCode);
        })
    })
})
相关问题