Jquery 在div中按顺序对项目进行编号

Jquery 在div中按顺序对项目进行编号,jquery,jquery-ui,Jquery,Jquery Ui,我想使用jQuery对div列表中的项进行编号。现在它们都是硬编码的(第1项、第2项、第3项……),但我希望jQuery对它们进行编号,因为我将使用jQuery UI的可排序插件进行重新排序,所以当项目移动时,我需要重新排序 这是我的HTML: <div class="my-sortable my-sortable-active"> <div class="my-content-block"> <div class="my-sortable-head

我想使用jQuery对div列表中的项进行编号。现在它们都是硬编码的(第1项、第2项、第3项……),但我希望jQuery对它们进行编号,因为我将使用jQuery UI的可排序插件进行重新排序,所以当项目移动时,我需要重新排序

这是我的HTML:

 <div class="my-sortable my-sortable-active"> 
  <div class="my-content-block">
    <div class="my-sortable-header">Item 1: [Title Field] </div>
    <div class="my-sortable-body"> HELLO </div>
  </div>
  <div class="my-content-block">
    <div class="my-sortable-header">Item 2: [Title Field] </div>
    <div class="my-sortable-body"> HI </div>
  </div>
  <div class="my-content-block">
    <div class="my-sortable-header">Item 3: [Title Field] </div>
    <div class="my-sortable-body"> ANOTHER HELLO </div>
  </div>
</div>

项目1:[标题字段]
你好
项目2:[标题字段]
你好
项目3:[标题字段]
另一个你好
我有这个jQuery,但每个条目都编号为“条目1”,而不是1、2、3等:

$('.my-sortable-active .my-sortable-header').each(function() {
    $('.my-sortable-active .my-sortable-header').prepend("<span>" + ($(this).index() +1) + "</span>");
});
$('.my sortable active.my sortable header')。每个(函数(){
$('.my sortable active.my sortable header').prepend(“+($(this.index()+1)+”);
});
根据您直接从
each()
回调中获取元素的索引,因此使用以下方法:

$('.my-sortable-active .my-sortable-header').each(function( index ) {
    $(this).prepend("<span>" + (index +1) + "</span>");
});
$('.my sortable active.my sortable header')。每个(函数(索引){
$(this.prepend(“+(index+1)+”);
});
$('.my sortable active.my sortable header')。每个(函数(索引){
$(this.prepend(“+($(this.index()+1)+”);
});
$('.my sortable active.my sortable header')。每个(函数(索引){
$(this).prepend(“+parseInt(index+1)+“-”);
});
演示: 您也可以使用:

例如:

HTML: 删除“项目[计数器]”

这样就不需要额外的javascript,而且浏览器支持非常好()

哦,如果你列出了一些事情,请考虑使用<代码> UL> <代码>或<代码> <代码>标签,它们在你的情况下也很好。

$('.my-sortable-active .my-sortable-header').each(function(index) {
    $(this).prepend("<span>" + ($(this).index() +1) + "</span>");
});
$('.my-sortable-active .my-sortable-header').each(function(index) {
    $(this).prepend("<span>" + parseInt(index + 1) + " - </span>");
});
<div class="my-sortable my-sortable-active"> 
  <div class="my-content-block">
    <div class="my-sortable-header">[Title Field] </div>
    <div class="my-sortable-body"> HELLO </div>
  </div>
  <div class="my-content-block">
    <div class="my-sortable-header">[Title Field] </div>
    <div class="my-sortable-body"> HI </div>
  </div>
  <div class="my-content-block">
    <div class="my-sortable-header">[Title Field] </div>
    <div class="my-sortable-body"> ANOTHER HELLO </div>
  </div>
</div>
.my-sortable {
  counter-reset: section;
}

.my-sortable-header:before {
  counter-increment: section;
  content: "Item " counter(section) ": ";
}