javascript - 选择器的有效方法

标签 javascript jquery

我得到了这个结构:

<ul class="depth-one">
    <li>Category 1 <span class="do">+</span>
        <ul class="depth-two">
            <li > Category 1.1 <span class="do">+</span>
                <ul class="depth-three">
                    <li>Category 1.2.1</li>
                    <li>Category 1.2.2</li>
                </ul>
            </li>
            <li> Category 1.2</li>
            <li> Category 1.3</li>
        </ul>
    </li>
    <li> Category 2 <span class="do">+</span>
        <ul class="depth-two">
            <li>Category 2.1</li>
            <li>Category 2.2</li>
            <li>Category 2.3</li>
        </ul>
    </li>
    <li>Category 3 <span class="do">+</span>
        <ul class="depth-two">
            <li>Category 3.1</li>
            <li>Category 3.2</li>
            <li>Category 3.3</li>
        </ul>
    </li>
</ul>

使用那个 CSS:

ul{
    list-style:none;
    padding:0;
    margin:0;
}
ul li{
    width:220px

}
.depth-one{

}
.depth-two{
    display:none;
}
.depth-three{
    display:none;
}

.do{
    float:right;
    font-weight:bold;
    color:blue;
    cursor:pointer;
}

我想做的是,每当我点击类“do”(跨度)时,我都想切换 closet UL 元素。

我如何使用 jQuery 将最接近的 UL 元素选择到 span,以便我可以使用函数 slideUp 和 slideDown 来切换它?

我的想法是使用函数 next(),但我认为有更通用的方法来实现它。

提前致谢!

最佳答案

嗯,.next() 实际上是完美的

$('.do').on('click', function() {
    $(this).next('ul').slideToggle().find('ul:visible').slideUp(); // According to your comment; hide all the visible successors of type ul.
    $(this).text( $(this).text() == '+' ? '-' : '+' ); // Alter the caption (which I guess you want to do as well) :-)
});

编辑:为所有子 ul 添加隐藏以匹配您的评论。

关于javascript - 选择器的有效方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18099757/

相关文章:

javascript - 如何使用 JavaScript 交换表格中的图像位置?

javascript - 实际返回的是什么?

javascript - 元素被包装在父类的第一次出现中

javascript - 如何在angularJS列表中添加项目?

javascript - 处理音频文件

javascript - Owl Carousel 元素绝对位置

javascript - 无法在 Firefox 中设置默认焦点

javascript - 我设置ajax异步: false but not working

javascript - 如何编辑 URL 中的部分 anchor

javascript - 当 HTML Form 中隐藏了对应的控件时,Label 可以在 Tab 键切换时获得焦点吗?