2012-08-24 33 views
0

jQuery的導航欄,我想將導航欄添加到我的所有頁面的頂部(使用Twitter的引導)auth用戶名

導航欄需要包含auth'd用戶的全名。

我有GET的REST服務/ auth/rest/user/fullname,它將以純文本形式返回「Jane Doe」。

我有多個頁面,所以我正在尋找一個解決方案,我可以在每個頁面上添加最少量的樣板代碼。

我從一個banner.html文件我的旗幟裝載使用

<script> 
    addBanner(); 
</script> 

任何建議/想法:這樣的事情在頁面的頂部:

<div id="banner"></div> 

,這在底部:

function addBanner() { 
    $('body').css("padding-top", "50px"); 
    $("#banner").load("/banner.html"); 
    // how to replace the <span id="fullname">&nbsp;</span> with Jane Doe? 
} 

編輯:我需要從banner.html文件加載旗幟的HTML。該文件具有ID = fullname的跨度,需要從ajax GET進行更新,並將html的整個「塊」插入id爲banner的div中。我無法讓這兩件作品。我得到ajax返回我的全名,我可以從一個靜態文件加載,但我如何加載,修改我通過ajax加載,然後插入到DOM?

回答

3

您可以使用jquery的html()text()方法。儘管text()速度稍微快了一點,但我更喜歡使用.html(),因爲如果您決定使用插入的文本添加任何html,將無法按預期的方式使用text()

$('#fullname').html('Jane Doe'); 
// OR 
$('#fullname').text('Jane Doe'); 

這將導致在同樣的事情:

<span id="fullname">Jane Doe</span> 
// which displays as 
Jane Doe 

但是,如果你想包含HTML內容,如<h1>Jane Doe</h1>的結果將是:

<span id="fullname"><h1>Jane Doe</h1></span> 
// but with html() it will display the text 
Jane Doe 
// whereas with text() it will display the text 
<h1>Jane Doe</h1> 

Difference-between-jquery-text-and-html是一個很好的博客這篇文章解釋得非常好。

Live DEMO

關於你的編輯,你應該只加載的旗幟和橫幅已被更新之後更新用戶信息。你的附加功能的橫幅是這樣的:

function addBanner() { 
    $('body').css("padding-top", "50px"); 
    $("#banner").load("/banner.html", function() { 
     $('#fullname').html('Jane Doe'); 
    }); 
} 
+0

我認爲你應該使用的.text(),而不是html的() – kannix

+0

@kannix任何特別的原因?你可以使用任何一個。 –

+0

它應該更快http://jsperf.com/jquery-text-vs-html/11 – kannix

0

我去了這一點:

<script type="text/javascript"> 
    $(function() { 
     $("#banner").load("banner.html"); 
     $('body').css("padding-top", "50px"); 
     $.ajax({ 
      url : "/auth/rest/user/fullname", 
      cache : false 
     }).done(function(html) { 
      $('#fullname').html(html); 
     }); 
    }); 
</script> 
相關問題