1

ページの見出し(現在のみ)の目次(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>   
4

1 に答える 1

3

documentFragementパフォーマンス上の理由から、最初 に追加する必要があります。

    var frag = document.createDocumentFragment();
    $("h2").each(function (i, el) {
        var li = document.createElement( "li" );
        var $a = $("<a>", { id: "h2_" + i }).text( $(el).text() );
        li.appendChild( $a[0] )
        frag.appendChild( li );
    });
    $("ol").append(frag);
​

http://jsfiddle.net/landau/RyeAA/

http://jsfiddle.net/landau/RyeAA/5/-更新されたバージョン

于 2012-05-27T14:23:08.827 に答える