尝试构建一个插件效果,准备好后看起来会比这更好。
注意数字0
、1
、2
。
它们是元素当前所处级别的简单指示。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);
});
顺便说一句。你并不是在树上上下移动,而是始终保持在同一水平面上。
关于jquery - 有效地沿着上下 sibling 遍历,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9210783/