是否有可能實現一個使用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。
是否有可能實現一個使用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。
您可以使用.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>
您可以遍歷所有的錨和索引添加到使用.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>
爲什麼需要'.each()'? '.html()'迭代jQuery對象的所有元素。 – guest271314
這是OP問題的另一個解決方案:) –
使用此代碼,
<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>
javascript的答案不同於javascript的http://stackoverflow.com/a/41384631/? – guest271314
@ user7354735請不要重複的答案。 –
這不是重複的答案,我只是表明這是適合把jQuery的功能 – user7354735
純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>
對於元件中的每一個,設置文字,然後增加的數量。 – Seano666
所以選擇元素,循環,並添加文本? – epascarello