jquery 顺序导航



我需要获取点击列表项的索引号,该索引项可能嵌套在另一个UL中。

除嵌套 UL 的情况外,代码工作正常。 由于您同时单击父 LI 和子 LI,因此它将返回两个结果。 当我尝试使用锚标记而不是 LI 时,结果为 -1,因为锚点位于 LI 内部。

小提琴: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 );

我正在尝试扁平化层次结构以创建顺序导航(幻灯片和键绑定将绑定到此索引号)。 因此,我想要的数字基本上是LI的数字,如果列表是平坦的。

事件传播到其父级。您需要停止传播,您可以使用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,它也将覆盖其所有子项的样式,相反,您可以在锚点上应用样式,如果您希望锚点覆盖整个宽度,只需提供锚点的样式作为display:block

li > a{
    display:block;
}

演示

最新更新