有没有办法找出我点击的div的nth:child?
$('#divStatus div').on('click', function() {
console.log($(this).parents().eq())
})#divStatus div {
display: inline-block;
background: red;
width: 100px;
height: 100px;
}<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="divStatus">
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
</div>
发布于 2016-07-12 15:45:48
是的,使用jQuery的index函数。index是从0开始的,而:nth-child是从1开始的,所以您必须考虑到这一点。
$('#divStatus div').on('click', function() {
console.log($(this).index() + 1);
})#divStatus div {
display: inline-block;
background: red;
width: 100px;
height: 100px;
}<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="divStatus">
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
</div>
发布于 2016-07-12 15:45:32
为此,请使用index()函数。
查看此处
HTML:
<div id="divStatus">
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
</div>CSS:
#divStatus div {
display: inline-block;
background: red;
width: 100px;
height: 100px;
}JS代码:
$('#divStatus div').on('click', function() {
var nth = $(this).index() + 1;
console.log(nth)
})index()从0开始,在本例中,您需要从1 ( nth-child(1) )开始,这就是为什么要在index()中加1的原因
阅读有关index() here的更多信息
发布于 2016-07-12 15:45:32
使用.index()函数获取当前点击的div的索引:
索引将是从零开始的,因此您需要在其上加上+1才能获得正确的索引。
$(document).ready(function() {
$('#divStatus div').click(function() {
var index = $(this).index() + 1;
console.log(index);
});
});#divStatus div {
display: inline-block;
background: red;
width: 100px;
height: 100px;
}<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.0/jquery.min.js"></script>
<div id="divStatus">
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
</div>
https://stackoverflow.com/questions/38322769
复制相似问题