2016-12-17 182 views
0

我正在使用Jquery進行一個小型項目,並且遇到了問題。根據標題名稱動態地添加ID到標題?

我試圖創建一個小的腳本,將看一個頁面,並自動分配基礎上的標題文字的ID,以H1標題,即:

<h1> This is a Test </h1> 

<h1 id="This_is_a_Test"> This is a Test</h1> 

我已經能夠選擇每個H1,但是我還沒有能夠根據標題文本修改ID。

var $headers = $('.body h1); 
$headers.attr("id", not sure exactly how to pass headers text to this?); 

我明顯是一個新手,但會感謝一些幫助! 謝謝!

回答

0

使用jQuery的.attr()callback option讀取頭的文本,將其轉換爲蛇的情況下,並設置其爲id

var $headers = $('.body h1'); 
 
$headers.attr("id", function() { 
 
    return $(this) 
 
    .text() // get the h1 text 
 
    .trim() // remove spaces from start and the end 
 
    .toLowerCase() // optional 
 
    .replace(/\s/g, '_'); // convert all spaces to underscores 
 
}); 
 

 
console.log($headers[0]); 
 
console.log($headers[1]);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<div class="body"> 
 
    <h1>This is a Test </h1> 
 
    
 
    <h1>This is a another Test </h1> 
 
</div>

+0

謝謝Ori!這對我來說非常合適,評論幫助我消化正在發生的事情。我非常感謝你的幫助! –

0

首先,您需要通過使用text方法生成idh1

var $headers = $('.body h1'); // select the element 
var text = $headers.text(); // get the text of the element 
var id = text.trim().split(' ').join('_'); // split by space and join using _ 
$headers.attr("id", id); 
0

如果您想要爲您頁面中的每個h1元素執行此操作,您可以執行類似操作:

$(function() { 
 
    $('h1').each(function() { 
 
    $(this).attr('id', $(this).text().replace(/ /g, '_')) 
 
    }); 
 
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<h1>Some text</h1> 
 
<h1>Some other text</h1>

功能將採取一切h1元件,for each它將設置id屬性(使用attr function)的該h1元件的text()的值(同時改變以下劃線每空間)。