2013-10-05 65 views
1

如何在jQuery中使用標題的最後一個字添加span元素。如何在word中添加span元素

我想輸出是這樣的:

<div class="hedererty"> 
    <h1>Lorem ipsum dolor sit amet, consectetuer adipiscing <span>elit</span></h1> 
</div> 

注:這是範例稱號。在我的網站標題正在改變與不同的頁面。

任何想法或建議嗎?謝謝。

+0

見這會給你你正在尋找的答案:http://stackoverflow.com/questions/7075397/select-last-word-in-a-container':) ' –

+0

和http://stackoverflow.com/questions/1788939/jquery-find-and-wrap-textnode-with-some-element – zamnuts

回答

4

嘗試

$('.hedererty h1').html(function(idx, html){ 
    return html.replace(/(\w+)$/, '<span>$1</span>') 
}) 

演示:Fiddle

$('.hedererty h1').html(function (idx, html) { 
    return html.replace(/(\s[\S]+)$/, '<span>$1</span>') 
}) 

演示:Fiddle

+0

非常感謝你:) – Rajnikanth

+1

我不知道這是由Rakinikanth問:D –

1

split()字符串,添加span在彈出的字符串和使用字符串連接在一起join()

$(".hedererty h1").html(function(){ 
    var mystring= $(this).text().split(" "); //Split the string 
    var lastword = mystring.pop(); //Pop the last index value 
    return mystring.join(" ")+ (mystring.length > 0 ? " <span>"+ lastword + "</span>" : lastword); 
    //Return concatenated string 
}); 

Demo