【问题标题】:How to target a div by class name inside another class如何在另一个类中按类名定位 div
【发布时间】:2014-08-17 01:43:12
【问题描述】:

我有一些这样的 div。

<div class"parent">
    <div class"child">
     Some Stuff Here
    </div>
</div>


<div class"parent">
    <div class"child">
     Some other kinda Stuff Here
    </div>
</div>

我想单击父类并仅在该父类中显示子类,而不在其他父类中显示其他子类。

$(document).on('click', '.parent', function(){
    $(this).find($('.child').show(500));
});

【问题讨论】:

  • &lt;div class="parent"&gt;&lt;div class="child"&gt;... 您的标记无效,括号不匹配:$(this).find(&lt;selector&gt;).show(500); all .child 元素,而不仅仅是孩子
  • 使用$(this).find('.child').show(500);

标签: javascript jquery parent-child children css-selectors


【解决方案1】:

不要在 find 中使用选择器 $('.child'),因为它会返回 DOM 和 find 中的所有子元素,$(this).find($('.child').show(500)); 应该是 $(this).find('.child').show(500);

同样更正html,class"parent"应该是class="parent",同样适用于class"child"

Live Demo

$(document).on('click', '.parent', function(){
    $(this).find('.child').show(500);
});

【讨论】:

    【解决方案2】:

    首先,您需要更正您的标记,因为属性class 与其值之间应该有=。所以标记应该是这样的:

    <div class="parent">
        <div class="child" >
         Some Stuff Here
        </div>
    </div>
    

    试试这个:

    $(document).on('click', '.parent', function(){
        $(this).children('.child').show(500);
    });
    

    Demo

    【讨论】:

      【解决方案3】:

      您需要将 HTML 更正为

      <div class="child">
      

      您的标记中缺少'='

      下面一行就足够了:

      $(document).on('click', '.parent', function(){
         $(this).find('.child').show(500);
      });
      

      【讨论】:

        【解决方案4】:

        将选择器字符串传递给find(),而不是对象 - 您正在传递一个 jQuery 对象。您的 HTML 也无效,因为 class"parent" 应该是 class="parent"

        Demo

        $(document).on('click', '.parent', function(){
            $(this).find('.child').show(500);
        });
        

        【讨论】:

          猜你喜欢
          • 2013-07-11
          • 2021-12-21
          • 2012-02-16
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2013-11-13
          相关资源
          最近更新 更多