我的HTML如下所示。
<div class="col-md-12 line">
<span class="d1 available " seatid="515" seatname="A1"></span>
<span class="d1 available " seatid="516" seatname="A2"></span>
<span class="d1 available " seatid="555" seatname="A3"></span>
<span class="d1 available " seatid="556" seatname="A4"></span>
<span></span>
<span class="d1 available " seatid="517" seatname="A5"></span>
<span class="d1 available " seatid="518" seatname="A6"></span>
</div>
当我点击跨度时,我希望获得跨度索引与具有相同类别的所有其他跨度相比,
这意味着......
这是我现在要使用的代码。
var selector = $(this);
var selectIndex = selector.index();
答案 0 :(得分:1)
你应该将当前元素传递给index(),以便从当前所有可用范围中获取它的索引
因此您可以使用$("span.available").index($(this))
PS:避免直接在你的html标签上使用属性,你必须使用data-作为seatid和seatname =&gt; (data-seatid,data-seatname),您可以在jquery中使用dataset或data()来访问它们
见下面的代码段
$(function() {
$("span.available").on("click",function(){
console.log("index : " + $("span.available").index($(this)) + " seatid: "+$(this).data('seatid') );
})
})
&#13;
span {
display:block;
}
.as-console-wrapper {
max-height:75px;
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="col-md-12 line">
<span class="d1 available " data-seatid="515" data-seatname="A1">A1</span>
<span class="d1 available " data-seatid="516" data-seatname="A2">A2</span>
<span class="d1 available " data-seatid="555" data-seatname="A3">A3</span>
<span class="d1 available " data-seatid="556" data-seatname="A4">A4</span>
<span>empty</span>
<span class="d1 available " data-seatid="517" data-seatname="A5">A5</span>
<span class="d1 available " data-seatid="518" data-seatname="A6">A6</span>
</div>
&#13;
答案 1 :(得分:0)
var selectIndex = selector.parent().children('span.available').index(selector);