JQuery next() - 仅使用类获取下一个兄弟

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14895564/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 14:03:17  来源:igfitidea点击:

JQuery next() - Getting the next sibling using only classes

jqueryclassnextsiblings

提问by Edu

I'm trying to create something like a web accordion.

我正在尝试创建类似网络手风琴的东西。

Visual example:

视觉示例:

[TITLE DIV 1]
[CONTENT DIV 1]
[TITLE DIV 2]
[CONTENT DIV 2]
[TITLE DIV 3]
[CONTENT DIV 3]

I want to be able to toggle (jquery function toggle()) a "Content Div" by clicking on the respective "Title Div".

我希望能够通过单击相应的“标题 Div”来切换(jquery 函数 toggle())“内容 Div”。

I've tried the following, but it doesn't work.

我尝试了以下方法,但不起作用。

http://jsfiddle.net/Cs3YY/

http://jsfiddle.net/Cs3YY/

HTML:

HTML:

<div class="topSeparator"></div>
<div class="titleDiv">
    <h1>Title 1</h1>
</div>
<div class="bottomSeparator"></div>                 
<div class="contentDiv"><h2>Content 1</h2></div>

<div class="topSeparator"></div>
<div class="titleDiv">
    <h1>Title 2</h1>
</div>
<div class="bottomSeparator"></div>                 
<div class="contentDiv"><h2>Content 2</h2></div>

JQUERY:

查询:

$('.titleDiv').click(function() {       
        $(this).next('.contentDiv').toggle();
});

http://jsfiddle.net/Cs3YY/

http://jsfiddle.net/Cs3YY/

I would describe my function process as such:

我会这样描述我的功能过程:

  1. When you click on a element with a class named "titleDiv", do:
  1. 当您单击具有名为“titleDiv”的类的元素时,请执行以下操作:

1.1. Select that clicked element;

1.1. 选择被点击的元素;

1.1.1. Select the next sibling of that clicked element with a class named "contentDiv";

1.1.1. 使用名为“contentDiv”的类选择该单击元素的下一个同级;

1.1.1.1. Make the function toggle() act on this last element (With the class named "contentDiv");

1.1.1.1. 使函数 toggle() 作用于最后一个元素(使用名为“contentDiv”的类);

It seems that I'm wrong or I'm missing something.

似乎我错了,或者我遗漏了什么。

.

.

I'm including jquery 1.8.3 (Correctly).

我包括 jquery 1.8.3(正确)。

This works when using ID's instead of classes (I'm trying to avoid using them).

这在使用 ID 而不是类时有效(我试图避免使用它们)。

I placed an alert inside the click function and it works (The problem is inside it).

我在点击功能中放置了一个警报并且它可以工作(问题出在它内部)。

回答by Anton

Use .nextAll()and :firstto get the next contentDiv

使用.nextAll():first获取下一个 contentDiv

  $(this).nextAll('.contentDiv:first').toggle();

Demo here http://jsfiddle.net/Cs3YY/1/

演示在这里http://jsfiddle.net/Cs3YY/1/

回答by luxcem

Although, it's because next() select the bottomSeparator. You could use that trick

虽然,这是因为 next() 选择了底部分隔符。你可以使用这个技巧

$('.titleDiv').click(function() {       

    $(this).next().next().toggle();
});    

http://jsfiddle.net/Cs3YY/12/

http://jsfiddle.net/Cs3YY/12/