我想要得到被点击的孩子的索引
<div class="parent">
<div class="child">
<div class="c1"></div>
<div class="c2"></div>
</div>
<div class="child">
<div class="c1"></div>
<div class="c2"></div>
</div>
<div class="child">
<div class="c1"></div>
<div class="c2"></div>
</div>
</div>jQuery:
$('.child .c1').click(function(){
alert($(this).parent().index())
})我总是-1。我该怎么做呢?
编辑:
我试过这个:
$('.child .c1').click(function(){
alert($(this).index())
})结果一直是-1。有什么不对的?
发布于 2020-02-27 13:05:49
var child_index = '';
$('.c1').click(function() {
var parent = $(this).parent();
child_index = $(parent).index();
alert(child_index);
});.div{
position:absolute;
left:45%;
top:0;
}
.child{
margin:1%;
text-align:center;
background-color:gray;
width:100px;
height:100px;
}
.c1,.c2{
color:white;
background-color:blue;
}
.c2{
color:red;
}<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
<div class="div">
<div class="child">
<div class="c1">c1</div>
<div class="c2">c2</div>
<p>click only work on <strong>c1</strong></p>
</div>
<div class="child">
<div class="c1">c1</div>
<div class="c2">c2</div>
<p>click only work on <strong>c1</strong></p>
</div>
<div class="child">
<div class="c1">c1</div>
<div class="c2">c2</div>
<p>click only work on <strong>c1</strong></p>
</div>
</div>
var child_index = ''; //to store .child class parent index when clicked
$('.c1').click(function() {
var parent = $(this).parent(); //getting the specific parent of c1
//parent variable value now is = .child
child_index = $(parent).index();
alert(child_index);
});发布于 2013-08-15 16:59:11
它每次返回-1的原因是因为在jQuery-1中是false的布尔值,0是true。.index()主要询问元素是否存在。
如果你想找出它的号码,这是一个代码,我认为这是可行的。
var loop = $('.parent .child').length;
$('.child .c1').click(function(){
for(i=1; i<= loop; i++) {
if($(this).parent() === $('.parent').children().eq(i)) {
alert(i);
}
}
});发布于 2013-07-24 14:36:04
编辑,因为没有人能够重现问题,下面是一些可能性:
alert($(this).parent().prevAll().length);使用.prevAll获取所有以前的兄弟姐妹,然后使用该集的长度作为索引。
如果您希望为索引目的而忽略其他元素,则编辑使用.prevAll(".child")。
编辑您可以尝试将jQuery全部删除
var elms=document.getElementsByClassName("c1");
for(var i=0; i<elms.length; i++)
elms[i].onclick = function() {
var elm = this;
var index = 0;
elm = elm.parentNode;
if(elm) {
while(elm=elm.previousSibling) {
if(elm.nodeType == 1) {
index++;
}
}
} else {
alert("There's no parent node");
}
alert(index);
};https://stackoverflow.com/questions/17837057
复制相似问题