2010-11-10 32 views
1

使用JavaScript什麼是從其內容設置標題標識並使用連字符替換空格並使其成爲小寫字母的最簡單方法。使用JavaScript設置來自內容的標題ID屬性

例如,如果標題是:

<h1>Header one content</h1> 

我們如何才能改變這種狀況到:

<h1 id="header-one-content">Header one content</h1> 

感謝

回答

3

的另一種方式,通過所有H1標籤迭代以及執行操作:

$("h1").each(function() { 
    var hyphenated = $(this).text().replace(/\s/g,'-'); 
    $(this).attr('id',hyphenated); 
    } 
); 
1

既然你在標籤中提到的jQuery我假設你表示歡迎,所以:

jQuery("h1:first").attr("id", "header-one-content"); 

更新:對不起,沒讀過問題不夠仔細。這裏是一個更新:

從jQuery網站:

示例:設置ID爲基於頁面的位置的div。(編輯)

<h1>Heading One</h1> 
<h1>Heading Two</h1> 
<h1>Heading Three</h1> 

使用Javascript:

$("h1").attr("id", function (arr) { 
    return "header-" + arr; 
}); 

結果:

<h1 id="header-0">Heading One</h1> 
<h1 id="header-1">Heading Two</h1> 
<h1 id="header-2">Heading Three</h1> 

更多信息:jQuery.attr

+0

我覺得「 header-one-content「應該被編程提取。 – 2010-11-10 15:54:30

+1

......你讀過這個問題了嗎? – 2010-11-10 15:55:18

+0

@Gunner,啊編程..張貼從jQuery網站這樣做與divs的例子。 – kovshenin 2010-11-10 15:56:01

0

使用JQuery:

var inner = jQuery("h1:first").html(); 
inner.replace(" ", "-"); 
jQuery("h1:first").attr("id", inner); 
1

由於jQuery是不是真的需要

var tags = document.getElementsByTagName("h1"); 
for (var i=0, h1; h1 = tags[i]; i++) { 
    h1.id = h1.innerHTML.toLowerCase().replace(" ", "-"); 
} 
+0

這是最好的答案,因爲問題要求最簡單(不需要jQuery),但是,一行是不正確的:它應該是h1.id = h1.innerHTML.toLowerCase()。replace(//g,「 - 「); – Jeff 2010-11-10 16:09:44

+0

'「你好」「.replace(」「,」 - 「)'outputs'」你好 - 你「'。字符串的替換方法需要RegExp或字符串。 https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/String/replace – 2010-11-10 16:17:17

0

使用JavaScript:

var title = document.getElementsByTagName('h1')[0]; 
//it returns a array of h1 tags. For this example I only obtain the first position. 
//you can change the index of the array to obtain your 'h1'. It depends on the position. You also can to cover the array by a for loop. 

title.id = title.innerHTML.replace(/ /g, "-").toLowerCase() 
//The /g operator is to define a global replace.