2

我有几个不同的 div 看起来都像这样。

$(document).ready(function() {
  $(".show").click(function() {
    $(".show").parent().(".text").toggle();
  });
});

<div class="container #{i}">
    <div class="show">
        show
    </div>

    <div class="text">
        text text text
    </div>
</div>

我希望能够单击显示,并让它只在其容器 div 中切换文本 div。我想我可以用我点击的类“show”来获取元素的父类,这将是容器+索引,然后在该容器 div 中获取名为“text”的子类。

老实说,这感觉相当微不足道,但我在 Javascript 方面还不是很有经验,而且我不确定要搜索的措辞。我将不胜感激任何帮助。:)

4

5 回答 5

3

有查找功能

$(document).ready(function() {
  $(".show").click(function() {
    $(this).parent().find(".text").toggle();
  });
});
于 2013-03-20T17:58:10.127 回答
1

您可以使用该siblings函数获取/过滤同一级别的元素:

jQuery('.show').click( function () {
   jQuery(this).siblings('.text').toggle(); 
});

更多信息:http ://api.jquery.com/siblings/

于 2013-03-20T17:59:42.947 回答
1

您非常接近,您只需要在父级上调用“查找”并替换.show选择器,this因为您只想切换.text当前(此)父级内部的 div,而不是全面切换。所以你需要这样的东西:

$(document).ready(function() {
  $(".show").click(function() {
    $(this).parent().find(".text").toggle(); //replaced .show for this
  });
});

或另一种选择(尽管其他人已经发布了)

$(".show").siblings(".text").toggle();

但是,要使上述方法起作用,两个 div(.show 和 .text)必须处于同一级别,而find, 即使.text嵌套在另一个元素中也会找到它。

于 2013-03-20T18:00:28.073 回答
0

你不应该抓住父母......

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

应该管用。只是抓住了兄弟姐妹。

于 2013-03-20T17:59:10.897 回答
0

你可以在 .click 函数中试试这个

$(this).parent().find("text").toggle();
于 2013-03-20T18:00:22.893 回答