2017-07-07 30 views
0

我正在使用nakupanda bootstrap3-dialog庫進行模態操作。下面是用於創建和顯示對話框代碼:jQuery選擇器無法在.load()中完成回調

function createIncommingCallDialog(msg){ 
    offermsg = msg; 
    incommingCallDialog = new BootstrapDialog({ 
     message: $('<div></div>').load('./RemoteDialog.html', function() { 
     //this code is not working. Neither .text() nor .click() has any 
     //affect. 
     $('.caller').text(offermsg.from); 
     $('.incomming').text('incoming call'); 
     $('#accept').click(function(){ 
      incommingCallDialog.close(); 
     }); 
     $('#decline').click(function(){ 
      incommingCallDialog.close(); 
     }); 
     }), 
     closable: false, 
    }); 
    incommingCallDialog.realize(); 
    incommingCallDialog.getModalFooter().hide(); 
    incommingCallDialog.getModalHeader().hide(); 
    incommingCallDialog.getModalBody().css('background-color', '#1A1A1A'); 
    incommingCallDialog.getModalBody().css('color', '#fff'); 
    incommingCallDialog.open(); 
} 

我使用jQuery的.load()方法加載遠程HTML的對話框中,它完成時我設置的div和按鈕的文字和聽衆。但沒有任何反應。 .text()和.click()在完整回調中都沒有任何影響,並且在控制檯中沒有錯誤。怎麼了?

+0

事件委派問題? – guradio

+0

你做了一個'console.log'來檢查函數是否完成? – Lewk

+0

是的,它正在完成...我想出了問題,並在下面發佈了一個答案 –

回答

3

我剛纔發現了這個問題。此代碼

message: $('<div></div>').load('./RemoteDialog.html', function() { 
    //this code is not working. Neither .text() nor .click() has any 
    //affect. 
    $('.caller').text(offermsg.from); 
    $('.incomming').text('incoming call'); 
    $('#accept').click(function(){ 
     incommingCallDialog.close(); 
    }); 
    $('#decline').click(function(){ 
     incommingCallDialog.close(); 
    }); 
    }), 

在尋找主文檔中的DOM元素(.caller,.incomming,#accept等),有時也找不到他們,因爲他們被裝內$('<div></div>')並沒有連接到主要文件。所以我改變了代碼如下:

message: $('<div></div>').load('./RemoteDialog.html', function() { 
     $(this).find('.caller').text(offermsg.from); 
     $(this).find('.incomming').text('incoming call'); 
     $(this).find('#accept').click(function(){ 
      incommingCallDialog.close(); 
     }); 
     $(this).find('#decline').click(function(){ 
      incommingCallDialog.close(); 
     }); 
     }), 

現在,它的作品...

相關問題