2011-03-10 80 views
0

我目前工作的一個網站上,我想在JavaScript中創建一個模式彈出窗口。問題是,我想從單獨的.html文件中取出窗口的內容,而不是從頁面上的隱藏div中取出(這是我見過的大多數示例都告訴你如何去做)。如何用Javascript中的外部文件創建模態彈出窗口?

我會很感激,如果有人可以就如何落實這正確的方向指向我。

在此先感謝

馬特d

回答

1

如果使用jQuery(你應該)

var div = $('#myid'); // container for the content 

$.get(url)      // get the content 
.success(function(resp) {  // on success 
    $(div) 
     .html(resp)    // populate the div 
     .dialog({ modal: true }); // and turn it into a dialog 
}); 

注意:這個例子用了jQuery 1.5的新的 「延期」 的語法。如果使用較早的函數,則根據情況將處理程序作爲參數傳遞給$.get

1

假設HTML文件在同一個域中的網站(因爲跨域請求將無法正常工作),就可以發起一個Ajax請求檢索數據並將其插入到包含元素中。

儘管你不需要使用jQuery(或任何其他庫,爲此事)來處理Ajax請求和響應,這使得它具有跨瀏覽器的細微差別,尤其是在處理時容易得多。

你可以做這樣的事情(假設基於myModel現在沒有的顯示):

// Initiate a request to the HTML file 
$.get('url-to-file-.html', function(data) { 

    // Insert the returned data into an element with 
    // the ID of myModel and then show it. 
    $('#myModel').html(data).show(); 

}); 

簡單的例子,但應該這樣做。您可以在API頁面上看到jQuery $.get()的更多深入示例。

+1

和使用jQuery.UI的「對話」功能把#myModel成一個模式對話框。 – Alnitak 2011-03-10 14:06:52

1

您可以使用iframe彈出式窗口中顯示的另一頁。

2

湯姆的建議是一個很好的一個。你也可以使用jQuery的負載(http://api.jquery.com/load/)函數,這將直接load HTML到一個元素:

$(modelContainerId).load(pathToHtml+ " #sectionOfHtml", function (response, status, xhr) { 
    $.blockUI({ 
     message: $(modelContainerId), 
     css: { 
      border: 'none', 
      padding: '15px', 
      backgroundColor: '#000', 
      '-webkit-border-radius': '10px', 
      '-moz-border-radius': '10px', 
      opacity: .9, 
      color: '#fff', 
      top: ($(window).height() - 700)/2 + 'px', 
      left: ($(window).width() - 700)/2 + 'px', 
      width: '700px', 
      cursor: 'pointer' 
     } 
    }); 

    $('.blockOverlay').attr('title', 'Click to unblock').click($.unblockUI); 
}); 

這裏.load(pathToHtml+ " #sectionOfHtml"只加載ID從加載的HTML命名#sectionOfHtml 。我使用此功能以上下文敏感的方式加載不同的幫助頁面。

相關問題