jquery 使用 .each() 递增数字
如何使用 .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
how do i increment id using .each() function.
$("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});
});
let say, there are 3 checkboxes are checked! so the id will be incrementing until 3(1,2,3).
i forgot to mention var id_bookslot = data. data
which is an id that i retreive from database. let say it starts with 1234. and everytime .each() generate, it will increment by 1. 1234, 1235, 1236
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
each() 方法允许您使用元素的索引。这可能是实现这一目标的最佳方法。
我添加了 +1,因为索引是 0 索引,而您似乎希望它从 1 开始。
The each() method allows you to use the index of the element. That's likely the best way to accomplish this.
I added +1 since the index is a 0 index and you seem to want it to start at 1.
如果您的目标是为每个复选框执行
post
,并提供索引或平滑,each
为您提供一个可以使用的索引(另外,避免重复编写$(this)
,这是浪费的):另外请注意,
$(this).length
将始终为1
,但无论如何您都没有使用counter
变量,所以我只是将其删除。如果您使用它但只是没有引用代码,请执行以下操作:...并使用
checked.length
作为您的counter
变量。If your goal is to do a
post
for each checkbox, and to give an index or smoething,each
gives you an index you can use (also, avoid writing$(this)
repeatedly, it's wasteful):Also note that
$(this).length
will always be1
, but you weren't using yourcounter
variable anyway, so I just removed it. If you use it but just didn't quote the code that is, do this:...and use
checked.length
for yourcounter
variable.您必须将变量移到闭包之外:
虽然这可能有效,但对我来说总是有点 hack-y。您可能需要考虑另一种更简洁的方法来实现您的目标(例如使用传统的 for 循环,以便您可以使用当前索引)。
You would have to move the variable outside the closure:
While this may work, it always seems a bit hack-y to me. You might want to think about another cleaner way to accomplish your goal (like using a traditional for loop so you have the current index available to you).
使用闭包:
请注意,我删除了您的
count
变量,该变量始终为 1(回调中的$(this)
是迭代中的单个元素),并且从来没有用过的。Use the closure:
Note that I removed your
count
variable, which was always 1 ($(this)
inside the callback being the individual element in the iteration) and which was never used.