2012-08-24 31 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> 
相关问题