【问题标题】:how to select the right div in javascript using parent/child如何使用父/子在javascript中选择正确的div
【发布时间】:2013-03-20 17:54:49
【问题描述】:

我有几个不同的 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 方面还不是很有经验,而且我不确定要搜索的措辞。我将不胜感激任何帮助。 :)

【问题讨论】:

  • 使用:$(this).parent().find(".text").toggle();
  • 使用$(this).next().toggle() 而不是$('.show').parent().('.text').toggle()

标签: javascript jquery css class html


【解决方案1】:

有查找功能

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

【讨论】:

    【解决方案2】:

    可以使用siblings函数获取/过滤同级元素:

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

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

    【讨论】:

      【解决方案3】:

      您非常接近,您只需要在父级上调用“find”并将.show 选择器替换为this,因为您只想切换当前(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 嵌套在另一个元素中也会找到它。

      【讨论】:

      • :) 正是我所做的——感谢您的澄清!我之前不知道兄弟姐妹,但我已经简化了我发布的代码,所以他们实际上不在同一级别
      【解决方案4】:

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

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

      应该可以。只是抓住兄弟姐妹。

      【讨论】:

        【解决方案5】:

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

        $(this).parent().find("text").toggle();
        

        【讨论】:

          猜你喜欢
          • 2014-06-11
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2020-12-29
          • 1970-01-01
          • 1970-01-01
          • 2022-01-22
          • 1970-01-01
          相关资源
          最近更新 更多