过滤器嵌套的div使用jQuery

过滤器嵌套的div使用jQuery

问题描述:

这是HTML的结构,我有:过滤器嵌套的div使用jQuery

<div class="day"> 
    <div class="date"> 
     ... 
    </div> 
    <div class="event-container"> 
     <div class="event">...</div> 
     <div class="event">...</div> 
     ... 
     <div class="event">...</div> 
    </div> 
</div> 

我想通过.event内容过滤这种结构。如果搜索查询中的任何单词不在.event元素中,则必须隐藏它。如果隐藏了.event-container中的所有.event,则必须隐藏整个.day

这里是我的尝试:

var terms = query.split(" "); 

$('.day').each(function() {   //iterate over days 
    var matches = false;    //does the day contain a valid event? 

    $(this).find('.event').each(function() { //iterate over events of this day 
     var evMatches = true;   //does this event contain all terms? 

     $.each(terms, function (index, term) { //iterate over terms 
      if ($(this).text().search(new RegExp(term, "i")) < 0) 
       evMatches = false; //if any term isn't found, element is invalid 
     }); 

     if (evMatches) //if event contained query 
     { 
      matches = true; //day contains valid event 
      $(this).show(); 
     } 
     else 
      $(this).hide(); 

    }); 

    if (matches) //if day contains valid event 
     $(this).show(); 
    else 
     $(this).hide(); 
}); 

我得到 “未捕获的RangeError:超过最大调用堆栈大小”。

我相信我在$.each(terms, ...)$(this).find('event-entry').each(...)中做错了什么,因为我不太了解这些语句,只是试图从示例和jquery文档中组合这些语句。

this是不是你认为它是在terms循环内。它有一个新的上下文each迭代元素

在迭代字符串数组的每个循环中不能使用this

当你有嵌套循环存储任何this引用,所以你知道你正在处理哪个this

也可以尝试来存储值不会改变,所以你不必看同样的事情了很多很多次

$('.day').each(function() {   
    var matches = false;    

    var $day = $(this); // store `$(this)` reference 

    $day.find('.event').each(function() { 
     var evMatches = true;   

     var $event = $(this), eventText = $event.text(); 

     $.each(terms, function (index, term) { 
      // use stored text value instead of looking it up each time 
      if (eventText.search(new RegExp(term, "i")) < 0) 
       evMatches = false;  
     }); 

     if (evMatches) //if event contained query 
     { 
      matches = true; //day contains valid event 
      $event.show(); 
     } 
     else 
      $event.hide(); 

    }); 

    if (matches) //if day contains valid event 
     $day.show(); 
    else 
     $day.hide(); 
}); 
+0

啊'this'在我的'$ .each'是一样的作为任期,对吗?谢谢! –

+0

是否有任何约定或原因,为什么你将'$(this)'存储在''''''''''''''''''开始的变量中。 –

+1

不......它和'term'不一样。 '$'前缀是一个常用的约定,可以让你知道它是一个jQuery对象 – charlietfl