2013-06-06 82 views
0

我見過很多類似的問題,但沒有一個具體解決這個問題。使用JQuery加載頁面片段(使用片段CSS /腳本)

對於Web應用程序,我設計了許多特定的動態「片段」(例如,當前會話的登錄狀態)。這些片段被保存爲不完整的html(具體的不完整的jsp頁面)。他們沒有html或body標籤。但有CSS樣式的JavaScript文件是必要的片段工作。

Fragment.jsp

<script type="text/javascript"> 
[...]code and functions to use ajax request to load current name using sessions 
</script> 

<div id="userProfile"> 
<H1>Current User:<span id="name">NONE GIVEN</span></H1> 
</div> 

然後我們的目標是使用jQuery來加載當前頁面上的片段,添加CSS以保持它在右上角的固定位置。

  1. 關於動態加載這些碎片時的CSS。如果使用$(「#someID」).load()加載這樣的片段,那麼包含的CSS和JS鏈接會加載到當前容器中,從而導致html無效?

  2. 只使用url $(「#someID」).load(「/ fragments/Fragment.jsp #userProfile」)中的選擇加載片段,然後動態加載css和js。

我認爲,靜態地將代碼添加到頁面中應避免使用,因爲會導致必須更改多個頁面,導致unmanagable網站使用該片段的頁數。

回答

0

由於這似乎是另一個啞巴的問題,讓我把它和我使用的解決方案。請記住,它可能不正確,因爲我剛剛開始網頁設計。

- 我使用Tomcat和Servlets/JSP作爲服務器端,但這對創建和使用小部件沒有影響。

fragment.jsp

<div id="widget"> 
This contains the widget html. For the example here is a div to fill with data dynamically 
<div id="dynamic"></div> 
</div> 

fragment.js

function initiateFragment(){ 
    $.get(aUrl,function(data){ 
    //callback goes here 
    $("body").append(data); 
    $("#dynamic").html(//dynamic content for the div); 
    $("#widget").css(//Add any css here, don't include it to force modularity); 
    //Since I needed a login widget, I added css to move the div out of document flow and to the top right 
    }); 
} 

現在,只是我的主頁上調用initiateFragment()(確保fragment.js包括),片段負載和出現。