这个弹出来的 num怎么会是 -1啊
获取哪里错误了?
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<script type="text/javascript" src="script/jquery_2_1_3/jquery-2.1.3.min.js"></script>
<script>
$(function(){
$('.grays').click(function(){
console.log($(this).parent().index());
$(this).click(function(){
console.log('>>>'+$(this).parent().index());
});
});
});
</script>
</head>
<body>
<li>
<p>1</p>
<p><img src="imgs/bico-github.png" class="grays">2</p>
<p><img src="imgs/bico-jabber.png" class="grays">3</p>
<p><img src="imgs/bico-github@2x.png" class="grays">4</p>
</li>
</body>
</html>
$(this).parent().index()
获取指定DOM元素的父元素在其兄弟节点中的位置,那你的DOM树结构不会出现-1你贴出的代码在一个click事件回调中为当前相应事件的回调函数又绑定了事件,那么会导致随着你点击次数次数的增多,DOM元素上会重复绑定回调函数,你上面的代码看不来,是因为你执行的了
$(this).parent().remove();
; 为什么要这样写呢?
~请精简代码,把问题重现下吧~
这,你为毛在里面又写个事件绑定啊
$('.grays').clck(function(){
$(this).attr(....),
$(this).click(function(){
//嗯,就是这 为啥又绑定啊
})
//直接$(this).parent().index()不就拿到夫元素p的下标了吗
})
我记得用法应该是
$('.grays').index($(this))
你用法错了
$('.grays').on('click',function(){
var ts = $(this);
var num=$('p').index(ts);
alert(num);
});
没有必要去绑定两次click事件,会触发多次回调
$(this).index(); 试试
jquery 版本?像上次一样?