2013-02-13 68 views
1

在调用页面的时候,我用一个href绑定我的fancybox,像这样:多个事件处理程序创建重新开放的fancybox

<a id="myId" href="myContent.cfm">Click me</a> 
<script> 
    $(document).ready(function(){ 
     $('a#myId').fancybox({ 
      // my initialization params 
     }); 
    }); 
</script> 

在myContent.cfm,默认的“过滤器”的建成,其中有添加和删除按钮。事情是这样的:

<div id="fd_0" class="eachFilter blank"> 
    <select name="filterBy" class="fl filterBy"> 
     <option selected="selected">-- Add a Filter --</option> 
     <!--- add more options ---> 
    </select> 
    <button type="button" class="addFilter default" title="Add a filter to the current filter set.">+</button> 
    <button type="button" class="deleteThisFilter default" title="Delete this filter from the current filter set.">-</button> 
</div> 

当点击addFilter按钮,一个新的“默认”过滤器是用户点击,使用连续的ID的过滤器后添加到DOM。相反,单击deleteFilter按钮会导致该过滤器被删除,并且所有剩余的过滤器将其ID重新编号;除了必须剩下一个过滤器之外。我原来的代码中使用.live()将事件处理程序附加到新创建的元素,比如:用户已经创建的所有“过滤器”

$('.addFilter).live('click', function(){   
    // get number of existing filters 
    // create new blank filter 
    // add to the dom after the filter whose button was just clicked 
}); 
$('.deleteThisFilter).live('click', function(){  
    // if there is more than one existing filter, use .remove() to remove the parent .eachFilter div 
    // renumber the existing filter ids consecutively 
}); 

后,他们需要的,他们既可以“应用”它们,关闭fancybox并用新的过滤参数重新加载网格,或者直接取消并关闭fancybox。

这一切都第一次正常工作,并重新打开fancybox,初始空白过滤器的添加按钮按预期工作。但是,添加第二个过滤器后,添加到dom的任何过滤器都将多个事件处理程序添加到addFilter和deleteFilter按钮。如果我第一次添加一个过滤器,然后第二次返回到fancybox,然后通过单击默认过滤器的添加按钮添加一个过滤器,然后单击新创建的过滤器添加按钮,添加两个过滤器。如果关闭,再次打开fancybox,添加一个过滤器,然后单击该过滤器添加按钮,添加三个过滤器。

所以这里是我试过到目前为止:

1)更改.live()调用

$(document).on('click', 'addFilter', function(){ // add my filter code}); 

2)把代码来创建过滤器转换成函数,最后使用.bind()将事件处理程序添加到新创建的过滤器;随后使用

$('.addFilter').unbind('click', fnCreateMyFilter()) 

关闭fancybox。

3)使用.live()仅在新创建的过滤器,以及一个常规的点击处理器默认元素

4)的jQuery升级到1.8.3从我们目前的版本

5)调用卸下摆臂()上的fancybox 内所有元素.onClosed功能(尽管我的印象那个关闭的fancybox确实从dom中删除了这些元素)。

有什么想法?

+0

我注意到.live()实际上是在jQuery 1.7中进行了描述。 – HeyWatchThis 2013-11-18 22:03:02

回答

1

一如既往,这是最明显的不明显的事情。移动。js将弹出窗口编码到它自己的文件中解决了这个问题,这是我在完成所有代码工作后打算做的事情。

+0

谢谢兄弟!每当我关闭一个fancybox并打开一个新的,它打开了迄今为止打开的量的两倍(而不仅仅是一个)......正在窃取我的垃圾^^ – natli 2015-07-13 11:08:06

0

我在使用Fancybox2 http://fancyapps.com/fancybox/和Noty弹出窗口http://needim.github.com/noty/的组合,并且有类似的问题。

我在href链接中使用class='fancybox.ajax'通过ajax将产品编辑表单加载到fancybox中。

当我点击我的保存按钮,直到我重新加载fancybox中的另一个(或相同)产品时,一切都很好保存。

我使用此代码触发我保存按钮:

$(document).on("click",".save_product_button",function(){ 
    ... post to ajax file to save info 
}); 

使用触发多个noty弹出式广告和(每次我会装,因为刷新的fancybox时间一次)保存,因为保存按钮是已经多次加载到文档模型中。 (我猜?)

但是,当我改变我的on()保存按钮的直接父母,我的所有问题都消失了。

$("#productBox").on("click",".save_product_button",function(){ 
    ... post to ajax file to save info 
}); 

从此以后一切都保存了一次。

另外,这应该使代码更快一点。

希望这可以帮助别人像我一样不浪费半天的时间。

相关问题