javascript – 获取并显示选中的复选框索引

用户每次使用Jquery检查复选框时,我试图显示复选框位置.例如,当用户检查星期一时,它将显示位置0,当用户检查星期日时,它将显示位置6.我找不到办法.我曾尝试使用.index()但它一直向我显示0.如何做到这一点的任何想法?

HTML代码

<div class="col-sm-9 checkBox_days">
    <label class="checkBox">
        <input type="checkBox" class="day" name="day[]" value="Monday"> Monday
    </label>
    <label class="checkBox">    
        <input type="checkBox" class="day" name="day[]" value="Tuesday"> Tuesday
    </label>
    <label class="checkBox">
        <input type="checkBox" class="day" name="day[]" value="Wednesday"> Wednesday
    </label>
    <label class="checkBox">
        <input type="checkBox" class="day" name="day[]" value="Thursday"> Thursday
    </label>
    <label class="checkBox">                        
        <input type="checkBox" class="day" name="day[]" value="Friday"> Friday
    </label>
    <label class="checkBox">                        
        <input type="checkBox" class="day" name="day[]" value="Saturday"> Saturday
    </label>
    <label class="checkBox">                        
        <input type="checkBox" class="day" name="day[]" value="Sunday"> Sunday
    </label>
</div>

JQuery的

$('.day').on('change', function() {
    $(this).each(function() {
        if (this.checked) {
            alert($(this).index());
        } else {
            alert("unchecked");
        }
    });
});

解决方法:

您需要使用.index(element)在列表中查找元素索引.

$('.day').index(this)

If no argument is passed to the .index() method, the return value is an integer indicating the position of the first element within the jQuery object relative to its sibling elements.

$(function() {
  $('.day').on('change', function() {

    if (this.checked) {
      alert($('.day').index(this));
    } else {
      alert("unchecked");
    }

  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="col-sm-9 checkBox_days">
  <label class="checkBox">
    <input type="checkBox" class="day" name="day[]" value="Monday">Monday
  </label>
  <label class="checkBox">
    <input type="checkBox" class="day" name="day[]" value="Tuesday">Tuesday
  </label>
  <label class="checkBox">
    <input type="checkBox" class="day" name="day[]" value="Wednesday">Wednesday
  </label>
  <label class="checkBox">
    <input type="checkBox" class="day" name="day[]" value="Thursday">Thursday
  </label>
  <label class="checkBox">
    <input type="checkBox" class="day" name="day[]" value="Friday">Friday
  </label>
  <label class="checkBox">
    <input type="checkBox" class="day" name="day[]" value="Saturday">Saturday
  </label>
  <label class="checkBox">
    <input type="checkBox" class="day" name="day[]" value="Sunday">Sunday
  </label>
</div>

相关文章

页面搜索关键词突出 // 页面搜索关键词突出 $(function () {...
jQuery实时显示日期、时间 html: &lt;span id=&quot...
jQuery 添加水印 &lt;script src=&quot;../../../.....
中文:Sys.WebForms.PageRequestManagerParserErrorExceptio...
1. 用Response.Write方法 代码如下: Response.Write(&q...
Jquery实现按钮点击遮罩加载,处理完后恢复 思路: 1.点击按...