jquery - 有效地沿着上下 sibling 遍历

标签 jquery jquery-selectors tree-traversal

a simple demo

尝试构建一个插件效果,准备好后看起来会比这更好。

注意数字012

它们是元素当前所处级别的简单指示。0 表示最高级别,2 表示最低级别。查看演示 here

每次我单击一列时,它都会成为主列(因此获得 0 作为其级别),其余列将使用相同的规则进行级别调整。如果您看到我用来执行此操作的代码片段,它非常难看。

$("li").click(function() {
    $(this).html(0);

    //denote the first level
    $(this).next().html(1);
    $(this).prev().html(1);

    //denote the second level
    $(this).next().next().html(2);
    $(this).prev().prev().html(2);    

    //denote the third level
    $(this).next().next().next().html(3);
    $(this).prev().prev().prev().html(3);    

    //denote the fourth level
    $(this).next().next().next().next().html(4);
    $(this).prev().prev().prev().prev().html(4);    
});

我绝对讨厌它。如果我的专栏数量增加了怎么办,那我就有麻烦了。我需要一些简洁的东西来遍历树结构(即像 .closest("li"))和下面的树结构。 对于每一列,一旦主列发生更改,就会获取其特定级别的标记。

最佳答案

您可以使用prevAll [docs]nextAll [docs] :

$(this).prevAll().each(function(i) {
    $(this).text(i+1);
});

$(this).nextAll().each(function(i) {
    $(this).text(i+1);
});

DEMO

顺便说一句。你并不是在树上上下移动,而是始终保持在同一水平面上。

关于jquery - 有效地沿着上下 sibling 遍历,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9210783/

相关文章:

jQuery 获取与类最接近的 div

java - 使用 Java PriorityQueue 实现级别顺序遍历二叉搜索树时出错

java - 遍历二叉树时出现空指针

javascript - 停止/静音音频

javascript - 如何检测 Angular 4中的浏览器后退点击

jquery - 如何根据alt属性判断图片是否存在?

关于遍历二叉树的C++设计题

用于按容器宽度/高度截断长文本字符串的 jquery 插件

jquery - 元素从鼠标下方移出后悬停状态是粘性的(在所有浏览器中)

jQuery 选择器 $ ('table td:eq(2) a' ) 仅从第一行获取单元格