[英]Set header id attribute from content with JavaScript
使用JavaScript,最簡單的方法是從其內容中設置標頭ID,並為連字符交換空格並使其小寫。
例如,如果標頭為:
<h1>Header one content</h1>
我們如何將其更改為:
<h1 id="header-one-content">Header one content</h1>
謝謝
由於確實不需要jQuery
var tags = document.getElementsByTagName("h1");
for (var i=0, h1; h1 = tags[i]; i++) {
h1.id = h1.innerHTML.toLowerCase().replace(" ", "-");
}
另一種方法,遍歷所有H1標簽並執行操作:
$("h1").each(function() {
var hyphenated = $(this).text().replace(/\s/g,'-');
$(this).attr('id',hyphenated);
}
);
由於您在標簽中提到了jQuery,因此我假設您對此表示歡迎,因此:
jQuery("h1:first").attr("id", "header-one-content");
更新 :對不起,沒有足夠仔細地閱讀問題。.這是一個更新:
從jQuery網站:
示例:根據頁面中的位置設置div的ID。 (編輯)
<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
使用JQuery:
var inner = jQuery("h1:first").html();
inner.replace(" ", "-");
jQuery("h1:first").attr("id", inner);
使用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.
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.