2016-12-29 11 views
4

jQuery/Javascriptを使用してタグのテキストを直接変更するカウンタを実装することはできますか?たとえば、私は2個のタグがあった場合:jQueryの/ JS関数を実行した後jQuery/Javascript相当のCSSカウンタ?

<a>hello</a> 
<a>bye</a> 

を、これは何が起こるかです:私はへのスクリプトを必要とするよう

<a>[1]hello</a> 
<a>[2]bye</a> 

私は、CSSカウンタを使用することはできません直接HTMLを編集します。

+0

、テキストを設定し、その後、番号をインクリメント。 – Seano666

+0

要素を選択し、ループし、テキストを追加しますか? – epascarello

答えて

5

あなたはすべてのアンカーをループ.html(function)

$("a").html(function(index, html) { 
 
    return "[" + (index + 1) + "]" + html; 
 
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"> 
 
</script> 
 
<a>hello</a> 
 
<a>bye</a>

1

を可能性が使用して.prepend()を使用してコンテンツにインデックスを追加することができます

$("a").each(function(index,value) { 
    $(this).prepend("["+(index++)+"] "); 
}) 

は、この情報がお役に立てば幸いです。

$("a").each(function(index,value) { 
 
    $(this).prepend("["+(index++)+"] "); 
 
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"> 
 
</script> 
 
<a>hello</a> 
 
<a>bye</a>

+0

'.each()が必要なのはなぜですか? '.html()'はjQueryオブジェクトのすべての要素を繰り返します。 – guest271314

+0

これは、OP質問の別の解決策です。 –

1

使用このコードは、純粋なJSで

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"> 
</script> 
<a>hello</a> 
<a>bye</a> 

<script> 
$("a").html(function(index, data) { 
    return "[" + (index + 1) + "]" + data; 
}) 
</script> 
+1

Answerで 'javascript'は' javascript'とどう違うのですか?http://stackoverflow.com/a/41384631/? – guest271314

+0

@ user7354735重複した回答は必要ありません。 –

+0

これは重複した答えではなく、私はちょうどjQuery関数を置くのに適している場所を示しています – user7354735

1

、あなたはテキストノードを作成して使用して取得する最初の子ノードとしてそれを挿入することができますカウンター - 以下のデモをご覧ください:

要素のそれぞれについて

Array.prototype.forEach.call(document.querySelectorAll("a"), function(e, i) { 
 
    e.insertBefore(document.createTextNode(`[${i+1}]`), e.childNodes[0]); 
 
});
<a>hello</a> 
 
<a>bye</a>