如何更改下面的文本,以便其中的文本附加一個數字。在jQuery中編號
<div class="right">This is some text</div>
<div class="right">This is some text</div>
<div class="right">This is some text</div>
所以上面的代碼會變得,
- 這是一些文本
- 這是一些文本
- 這是一些文本
如何更改下面的文本,以便其中的文本附加一個數字。在jQuery中編號
<div class="right">This is some text</div>
<div class="right">This is some text</div>
<div class="right">This is some text</div>
所以上面的代碼會變得,
以下情況如何?
$("div.right").each(function(i){
$(this).prepend((i + 1) + ". ");
});
UPDATE:
下面是應該工作的一種方式。
「number」是一個自定義元素(它可以是任何你想要的),瀏覽器將會/應該忽略它。
$("div.right").each(function(i){
$(this).find("number").remove().end()
.prepend("<number>(i + 1) + ". </number>");
});
,或者使用這可能是慢一點,但語義正確下面...
$("div.right").each(function(i){
$(this).find("span.number").remove().end()
.prepend("<span class='number'>" + (i + 1) + ". </span>");
});
或者甚至更好的方式是你的第一個阻力之前,預先考慮span.number:
$(function(){ // document ready...
// caching the "numbers" will only work if you use the DOM
// for updating div position (like jQuery's "append()", "prepend()", "before()", and "after()") and not "innerHTML" or "html()"
var numbers = $("div.right").each(function(i){
$(this).prepend("<span class='number'>" + (++i) + "</span>. ");
}).find("span.number");
function dragEnd(){
// do your drag end stuff here...
numbers.each(function(i){
this.innerHTML = ++i;
});
)};
});
+ 1-在我看來,這可能是最好的方法 – 2009-11-06 17:45:25
非常好,但有一個問題。每次div被重新排序時,都會添加一個新號碼,而不是替換現有號碼。如何解決這個問題? – usertest 2009-11-06 17:45:46
不知道重新排序。你必須讓他們在divs?你可以使用有序列表嗎? – 2009-11-06 17:49:34
這是否必須通過jquery動態完成?難道你不能只將所有文本合併到一個div中,然後在它周圍製作一個有序列表?
類將動態移動,所以他們需要動態地重新編號。 – usertest 2009-11-06 17:20:13
jQuery選擇是你的朋友? 讓您的東西,並循環通過這樣的事情:
texts = $("div.right");
for(i = 0;i < texts.length;i++)
{
node = $(texts[i]);
content = node.html();
number = i + 1;
node.html(number + ". " + content);
}
更新:哎呀,最後一次後未經測試的代碼直接在這裏下車圓頂(免責聲明:實際上不是最後一次)。爲了正確性,如果你仍然想這樣做,我已經更新它至少運行(並且工作!)。雖然我承認其他解決方案更清潔,更優雅。
這實際上是對另一個評論的闡述。我想,我無法在評論中格式化代碼。你可以使用jQuery核心的每一個:
$('div.right').each(function(ii){
html = $(this).html();
$(this).html(ii + '. ' + html);
});
它會將它們編號爲0,1,2而不是1,2,3。 – 2009-11-06 17:42:07
對結果集使用[]符號將爲您提供沒有html()函數的原始DOM元素。使用eq()函數來獲取包裝在jQuery對象中的每個元素。如果我在事件處理程序中,我也不必爲'this'調整。
var texts = $("div.right");
var elem;
for(i = 1; i < texts.length; i++) {
elem = texts.eq(i);
html = elem.html();
elem.html(i + '. ' + html);
}
爲什麼這些項目不在訂購清單中? – 2009-11-06 17:37:09