使用.each()的jquery增量号

时间:2011-04-20 13:07:13

标签: jquery checkbox increment

如何使用.each()函数增加id。

$("input:checked").each(function(){
var counter = $(this).length();
var id_bookslot = data; //<-- increment id +1
var treatment_type = $(this).closest("div").attr("id");
var id_treatment = $(this).attr("class");
$.post("include/get_booking.php?insert", {id_bookslot: id_bookslot,id_treatment:id_treatment,treatment_type:treatment_type});
});

让我们说,有3个复选框被选中!所以id将递增到3(1,2,3)。

我忘了提及var id_bookslot = data。 data这是我从数据库中检索的ID。让它说从1234开始。每次.each()生成,它将增加1. 1234,1235,1236

4 个答案:

答案 0 :(得分:6)

each()方法允许您使用元素的索引。这可能是实现这一目标的最佳方式。

$("input:checked").each(function( index ){
    var id_bookslot = index + 1; //<-- increment id +1
    var treatment_type = $(this).closest("div").attr("id");
    var id_treatment = $(this).attr("class");
    $.post("include/get_booking.php?insert", {id_bookslot: id_bookslot,id_treatment:id_treatment,treatment_type:treatment_type});
});

我添加了+1,因为索引是0索引,你似乎希望它从1开始。

答案 1 :(得分:3)

如果您的目标是为每个复选框执行post,并给出索引或smoething,each会为您提供一个可以使用的索引(同时,避免反复写$(this),这很浪费):

$("input:checked").each(function(index) {
  var $this = $(this);
  var id_bookslot = data + index + 1;          // <== Using the index here
  var treatment_type = $this.closest("div").attr("id");
  var id_treatment = $this.attr("class");
  $.post("include/get_booking.php?insert", {
      id_bookslot:    id_bookslot,
      id_treatment:   id_treatment,
      treatment_type: treatment_type
    }
  );
});

另请注意,$(this).length始终为1,但您仍未使用counter变量,因此我将其删除。如果您使用它但只是没有引用代码,请执行以下操作:

var checked = $("input:checked");
checked.each(function(index) {
  var $this = $(this);
  var id_bookslot = data + index + 1;          // <== Using the index here
  var treatment_type = $this.closest("div").attr("id");
  var id_treatment = $this.attr("class");
  $.post("include/get_booking.php?insert", {
      id_bookslot:    index,
      id_treatment:   id_treatment,
      treatment_type: treatment_type
    }
  );
});

...并使用checked.length作为counter变量。

答案 2 :(得分:2)

您必须将变量移到闭包之外:

var id_bookslot = 0;

$('input:checked').each(function(){
    id_bookslot++;
    // The rest of your code
});

虽然这可能有用,但对我来说似乎总是有点黑客。您可能想要考虑另一种更简洁的方法来实现您的目标(例如使用传统的for循环,以便您可以使用当前索引)。

答案 3 :(得分:1)

使用闭包:

var id_bookslot = 0;
$("input:checked").each(function() {

   id_bookslot++;

   var treatment_type = $(this).closest("div").attr("id");
   var id_treatment = $(this).attr("class");

   $.post("include/get_booking.php?insert", {
     id_bookslot:    id_bookslot,
     id_treatment:   id_treatment,
     treatment_type: treatment_type
   });
});

请注意,我删除了count变量,该变量始终为1(回调中的$(this)是迭代中的单个元素)并且从未使用过。

相关问题