2016-12-29 53 views
4

是否有可能實現一個使用jQuery/Javascript直接更改標籤文本的計數器?例如,如果我有2個標籤:相當於CSS Counter的jQuery/Javascript?

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

運行的jQuery/JS功能後,這是會發生什麼:

<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

使用此代碼,

<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

javascript的答案不同於javascript的http://stackoverflow.com/a/41384631/? – guest271314

+0

@ user7354735請不要重複的答案。 –

+0

這不是重複的答案,我只是表明這是適合把jQuery的功能 – user7354735

1

純JS,你可以使用創建文本節點並插入它作爲第一個子節點得到計數器 - 請參閱下面的演示:

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>