简体   繁体   English

jQuery find()无法与prev()一起使用

[英]jQuery find() not working with prev()

I'm probably doing it the wrong way so that is why I need your help. 我可能做错了方法,所以这就是为什么我需要您的帮助。 I have set up a jsfiddle here: https://jsfiddle.net/m35o8jjL/2/ 我在这里设置了一个jsfiddle: https ://jsfiddle.net/m35o8jjL/2/

HTML: HTML:

 $( ".layered_subtitle_heading" ).click(function() { $(this).prev().find('.layered_close').toggleClass('closed'); $(this).prev().find('.layered_filter_ul').toggle(); }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script> <div class="layered_filter"> <div class="layered_subtitle_heading clearfix"> <span class="layered_subtitle">Metall</span> <span class="layered_close"> <a href="javascript:;" data-rel="ul_layered_id_feature_9"></a> </span> </div> <ul id="ul_layered_id_feature_9" class="layered_filter_ul "> <li class="nomargin hiddable filter_lg"> <div class="checker" id="uniform-layered_id_feature_38"> <span> <input type="checkbox"> </span> </div> <label for="layered_id_feature_38"> <a href="#">925 Sterling Silber</a> </label> </li> </ul> </div> 

Basically , what I want is when user clicks on the layered_subtitle_heading div, class toggles of the layered_close span , same with the display of the ul . 基本上,我想要的是当用户单击layered_subtitle_heading div时, layered_close span类切换,与ul的显示相同。

I'm probably not using prev() correctly but I really can't think of any way to make this work. 我可能没有正确使用prev() ,但我真的想不出任何办法使它工作。

I have multiple layered_filters and that is why I have to use $(this) . 我有多个layered_filters ,这就是为什么我必须使用$(this)

The .prev() method is for navigating to the previous sibling . .prev()方法用于导航到上一个同级 Your target <div> does not have a previous sibling; 您的目标<div>没有先前的同级; it's the first child of its parent. 这是其父母的第一个孩子。

What you probably want to do instead is 您可能想做的是

$(this).parent().find('.layered_close').toggleClass('closed');

or, to be a little more resilient to change: 或者,更灵活地进行更改:

$(this).closest(".layered_filter").find('.layered_close').toggleClass('closed');

to fix it remove .prev() and add .siblings() to get the ul to toggle 要修复它,请删除.prev()并添加.siblings()以使ul切换

 $( ".layered_subtitle_heading" ).click(function() {
     $(this).find('.layered_close').toggleClass('closed');
     $(this).siblings('.layered_filter_ul').toggle();
     // you need to use alert()
     alert('da');
 });

and you hadn't added jQuery to your fiddle - https://jsfiddle.net/Jim_Miraidev/m35o8jjL/13/ 而且您还没有将jQuery添加到您的小提琴-https: //jsfiddle.net/Jim_Miraidev/m35o8jjL/13/

Try this 尝试这个

  $(document).ready(function(){
      $( ".layered_subtitle_heading" ).click(function() {
          $(this).parent().toggleClass('closed');
      });
  });

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM