在調用頁面的時候,我用一個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中刪除了這些元素)。
有什麼想法?
我注意到.live()實際上是在jQuery 1.7中進行了描述。 – HeyWatchThis 2013-11-18 22:03:02