jQuery-获取选定复选框的索引 [英] jQuery - Get the index of selected check box

查看:577
本文介绍了jQuery-获取选定复选框的索引的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

jQuery 1.7.1-我有一个复选框列,并希望以数组的形式获取所选框的索引,或者要遍历每个复选框-检查是否选中了该框,如果选中则获取了索引.

jQuery 1.7.1 - I have a check box column and would like to get the index of selected boxes as an array or iterate through each checkbox - check whether its selected or not, if selected get the index.

HTML

<tr>
  <td><input type="checkbox" class="it" name="it"></td>
</tr>
<tr>
  <td><input type="checkbox" class="it" name="it"></td>
</tr>

推荐答案

如果使用 .each()方法 jQuery会将索引作为参数传递给您提供的回调函数. (您可能会看到很多代码,这些代码在回调函数上使用.each()而不带参数,但这只是因为您通常不需要知道索引-而是在执行该操作时就可以使用.) jQuery函数将this设置为当前元素:

If you use the .each() method jQuery will pass the index as an argument to the callback function you supply. (You'll probably see a lot of code around that uses .each() without parameters on the callback, but that's just because you often don't need to know the index - but it's there for when you do.) Also when calling your function jQuery sets this to the current element:

$(".it").each(function(i) {
   if (this.checked) {
       alert("Checkbox at index " + i + " is checked.");
   }
});

请注意,索引是从零开始的,并且在不明显的情况下,它是与提供的选择器匹配的元素集中的索引(不是文档中的所有元素).

Noting that the index is zero-based, and in case it's not obvious it is the index within the set of elements that matched the selector you supplied (not within all elements in the document).

还请注意,上面我按类选择元素,但是您可以按name属性选择:

Note also that above I'm selecting elements by class, but you could select by the name attribute:

$('input[name="it"]')

这篇关于jQuery-获取选定复选框的索引的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆