我需要获取被点击的列表项的索引号,它可能嵌套在另一个UL中。
除嵌套 UL 的情况外,代码工作正常。由于您同时单击父 LI 和子 LI,因此返回两个结果。当我尝试使用 anchor 标记而不是 LI 时,结果为 -1,因为 anchor 位于 LI 内。
fiddle :http://jsfiddle.net/4Ww9C/
代码:
(function($) {
var manifest = $('#manifest li');
manifest.click(function(e){
$(this).addClass("active");
manifest.not(this).removeClass('active');
var selected = $(".active");
var pos = manifest.index(selected);
alert (pos);
});
}) ( jQuery );
我正在尝试展平层次结构以创建顺序导航(幻灯片和键绑定(bind)将绑定(bind)到此索引号)。所以我想要的数字本质上是你为 LIs 得到的数字,如果列表是扁平的。
最佳答案
事件传播到其父级。您需要停止传播,您可以使用 e.stopPropagation()
这样它就不会导航到其父级的点击事件(这会导致多个警报)。
manifest.click(function (e) {
e.stopPropagation();
.....
尝试:
(function ($) {
var manifest = $('#manifest li');
manifest.click(function (e) {
var $this = $(this),
pos;
e.stopPropagation();
manifest.find('.active').not($this.children('a').addClass("active")).removeClass('active');
pos = manifest.index($this);
alert(pos);
});
})(jQuery);
此外,如果您在 li
上应用 active,它也会覆盖其所有子项的样式,相反,您可以将样式应用于 anchor ,如果您希望 anchor 覆盖整个宽度,只需提供 anchor 样式为 display:block
li > a{
display:block;
}
关于javascript - jquery 顺序导航,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19776539/