JQuery next() - 仅使用类获取下一个兄弟 [英] JQuery next() - Getting the next sibling using only classes

查看:35
本文介绍了JQuery next() - 仅使用类获取下一个兄弟的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试制作类似网络手风琴的东西.

视觉示例:

[TITLE DIV 1][内容 DIV 1][标题 DIV 2][内容 DIV 2][标题 DIV 3][内容 DIV 3]

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

我尝试了以下方法,但没有用.

http://jsfiddle.net/Cs3YY/

HTML:

<div class="titleDiv"><h1>标题1</h1>

<div class="bottomSeparator"></div><div class="contentDiv"><h2>内容 1</h2></div><div class="topSeparator"></div><div class="titleDiv"><h1>标题2</h1>

<div class="bottomSeparator"></div><div class="contentDiv"><h2>内容 2</h2></div>

查询:

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

http://jsfiddle.net/Cs3YY/

我会这样描述我的函数过程:

  1. 当您点击类名为titleDiv"的元素时,请执行以下操作:

1.1.选择被点击的元素;

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

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

好像我错了或者我遗漏了什么.

.

我包括 jquery 1.8.3(正确).

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

我在点击函数中放置了一个警报并且它起作用了(问题出在它内部).

解决方案

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

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

此处演示 http://jsfiddle.net/Cs3YY/1/

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".

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

http://jsfiddle.net/Cs3YY/

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/

I would describe my function process as such:

  1. When you click on a element with a class named "titleDiv", do:

1.1. Select that clicked element;

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

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

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

.

I'm including jquery 1.8.3 (Correctly).

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

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

解决方案

Use .nextAll() and :first to get the next contentDiv

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

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

这篇关于JQuery next() - 仅使用类获取下一个兄弟的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
其他开发最新文章
热门教程
热门工具
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆