假设我在父元素中有未知数量的 div 元素。当我点击 child div 元素时,我想使用 console.log()
打印出它的 eq()
索引。
我不想使用任何类或 ID。
HTML:
<div id="parent">
<div></div><!--if I click on this element eq() should be 0-->
<div></div>
<div></div><!--if I click on this element eq() should be 2-->
<div></div>
<div></div>
</div>
JS:
$(this).click(
function(){
console.log(eqIndex);//now this div eq is a problem
}
);
CSS:
#parent div{
height: 10px;
width: 10px;
background-color:blue;
margin:2px;
}
最佳答案
尝试用元素选择器
绑定(bind)事件,并通过调用.index()
在这个对象上打印结果,
$('div').click(
function(){
console.log($(this).index());
}
);
$('div').click(
function() {
$("<p>").html($(this).index()).appendTo(document.body);
}
);
div {
height: 10px;
width: 10px;
background-color: blue;
margin: 2px;
}
<div></div>
<div></div>
<div></div><!--if I click on this element eq() should be 2-->
<div></div>
<div></div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
关于javascript - 获取元素 eq() 索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29793109/