2015-08-28 23 views
0

我在我們的引導程序中使用jQuery DataTables。我們有多個鏈接,其中包含針對它們的數據屬性。當模態被切換時,數據被提取出來,然後被添加到模態。與jquery和模態衝突的數據表

問題是,如果我們在數據表中進行搜索,那麼一旦鏈接被點擊,下面的程序就不會被調用。這可能是一個負載問題?任何想法如何解決它?

$('.modal-toggle').click(function(e){ 
    // get control 
    e.preventDefault(); 

    // get the vars from the data attributes 
    modalType = $(this).data('modal-type').toLowerCase(); 
    modalTitle = $(this).data('modal-title'); 
    modalText = $(this).data('modal-text'); 

    // add appropriate footer 
    if(modalType == "confirm"){ 
     modalUrl = $(this).data('modal-confirm-url'); 
     modalOptions = '<a href="' + modalUrl + '" class="btn btn-primary showhouse-colour white-text"><i class="icon-ok"></i> Yes</a><button class="btn" data-dismiss="modal" aria-hidden="true"><i class="icon-ban-circle"></i> No</button>'; 
    }else if(modalType == "alert"){ 
     modalOptions = '<button class="btn btn-primary showhouse-colour" data-dismiss="modal" aria-hidden="true"><i class="icon-ok"></i> OK</button>'; 
    }else if(modalType == 'form-confirm'){ 
     modalOptions = '<button class="btn showhouse-colour white" data-dismiss="modal" id="confirm-form-yes"><i class="icon-ok"></i> Yes</button><button class="btn" data-dismiss="modal" aria-hidden="true"><i class="icon-ban-circle"></i> No</button>'; 
    } 

    // set modal content 
    $('.modal-title').html(modalTitle); 
    $('.modal-text').html(modalText); 
    $('.modal-footer').html(modalOptions); 

    // if we have a confirm modalType 
    $('#confirm-form-yes').click(function(){ 
     $('.confirm-form').submit(); 
    }); 
}); 

回答

1

原因

數據表中刪除從DOM因各種原因不可見的行,以便當您將事件處理程序,它適用於目前唯一可見的元素。

SOLUTION

您需要通過作爲第二個參數提供選擇在on()調用中使用事件委託,見下面的例子,其中example是你的表ID。

$(document).ready(function(){ 
    $('#example tbody').on('click', '.modal-toggle', function (e){ 
     // ... skipped ... 
    }); 
}); 

從jQuery的on()方法文檔:

委派事件具有的優點是它們可以處理來自被添加到文檔在稍後的時間 後代元素事件。

請參見「直接和委託的事件」 jQuery的on()方法文檔和jQuery DataTables – Why click event handler does not work更多參閱。

+0

會/應該$('#dataTable_ID')足以抓住這個? –

+0

如果你的意思是$('#example')。on('click',',那麼答案是肯定的,只要你在頁眉或頁腳中沒有帶'modal-toggle'類的元素。 –

+0

。最後是有兩種方法可以調用它們,因爲有些可能不在數據表中。不想重複代碼。有沒有辦法調用這兩個函數或創建一個函數是最好的過程? $(' (''點擊','.modal-toggle',函數(e))點擊(功能(e){('#table_list_items')。 –