ページの見出し(現在のみ)の目次(as)を生成するスクリプトを作成しています。
リンクにhrefターゲットを割り当て、リンクのコンテンツとして変数を使用したいので、IDなしで要素を追加するのに問題があります。
私が取り組んでいるコード:
var h_num; // introduce the running id counter
$("h2").each(function (i) {
// retrieve the text contained in the element
$h_content = $(this).text();
// add a running id to the h2
$(this).attr("id", ("h2_"+i));
// the id attribute value that was just added to the element
$h_num = ("h2_"+i);
$new_id = ("#" + $h_num);
console.log($h_num, "hoonum", $new_id, "newid"); //for debugging
// append a <li> element with a link to the heading
$('#toc ol').append(
'<li>' + '<a href="$h_num">$h_content'
);
});
そのため、append関数内の行をエスケープする方法が見つかりません。
$ h_contentは見出しのタイトル(見出しへのリンクのテキストとして含まれる)であり、$new_idはhrefターゲットIDです。
目次のマークアップを次のようにしたいと思います
<ol>
<li><a href="#h2_0">First heading topic</a></li>
<li><a href="#h2_1">Second heading topic</a></li>
</ol>