检查这个小提琴http://jsfiddle.net/robincox/9nNej/34/,问题出在javaScript部分。或者您可以在此代码中看到它:
$(".off-canvas-list li:not(:has(ul))").addClass("liLast");
$(".off-canvas-list li").has("ul").addClass("liHasChild");
$("li.liHasChild > a").click(
function () {
if ($(this).siblings("ul").hasClass("opened")) {
// Here I want to find the sibling ul tag to the a tag I clicked.
// Then I want to check that ul tags children after an li with the class "liHasChild".
// If such a tag isn't found the value of 1 shall be stored in a variable named depth.
// If such a tag is found (an li with the class "liHasChild") then search it's child
// ul tag after an li with the class "liHasChild"
// If such a tag isn't found the value of 2 shall be stored in a variable named depth.
} else {
// Open clicked a tags sibling ul
$(this).siblings("ul").slideDown();
$(this).siblings("ul").addClass("opened");
}
}
);
$(".off-canvas-list ul").css("display", "none");
答案 0 :(得分:0)
尝试以下递归函数:
function depthOf(elem){
var $children = $(elem).siblings("ul").children("li.liHasChild");
if($children.length){ //If there are children with children
return 1 + depthOf($children.find("a")); //count and go deeper
}
return 1;
}
以下是如何使用它:
if ($(this).siblings("ul").hasClass("opened")) {
alert(depthOf(this));
}