2015-11-06 37 views
1

帮助!我花了一天的时间试图弄清楚这一点。查询搜索框查找div

// search function 
 
$(document).ready(function(){ 
 
    $("#bc").hide(); 
 
    $("#exerciseSearch").keyup(function(){ 
 
    
 
     // Retrieve the input field text and reset the count to zero 
 
     var filter = $(this).val(), count = 0; 
 

 
    
 
     // Loop through the comment list 
 
     $("#exercisesCont div").each(function(){ 
 
    
 
      // If the list item does not contain the text phrase fade it out 
 
      if ($(this).text().search(new RegExp(filter, "i")) < 0) { 
 
       $(this).fadeOut(); 
 

 
    
 
      // Show the list item if the phrase matches and increase the count by 1 
 
      } else { 
 
       $(this).show(); 
 
       count++; 
 
      } 
 
     }); 
 
    
 
     // Update the count 
 
     var numberItems = count; 
 
     $("#filter-count").text("Number of Comments = "+count); 
 
    }); 
 

 
});
<input type="text" class="form-control text-input" id="exerciseSearch" value=""> 
 
<div id='exercisesCont'> 
 
    <div id='1'> 
 
    <div>1</div> 
 
    <div>Turning this div to display:none</div> 
 
    </div> 
 
    <div id='2'> 
 
    <div>2</div> 
 
    <div>Turning this div to display:none</div> 
 
    </div>  
 
    <div id='3'> 
 
    <div>3</div> 
 
    <div>Turning this div to display:none</div> 
 
    </div> 
 
    <div id='4'> 
 
    <div>4</div> 
 
    <div>Turning this div to display:none</div> 
 
    </div> 
 
</div>

目前,当我搜索 '1' 与我的搜索功能,我得到的 '1' 的结果。这听起来不错,但它是为div 1的子元素中的'文本'。

我需要的是搜索Div ID(在div id'exerciseCont'内部)而不是搜索'text'并显示该div及其所有子元素(当前的同级元素正被转为显示:无)。

我希望有道理吗?预先感谢您的帮助!

回答

1

试试这个

$("#exercisesCont > div").each(function(){ 

     // If the list item does not contain the text phrase fade it out 
     if ($(this).children().eq(0).text().search(new RegExp(filter, "i")) < 0) { 
      $(this).fadeOut(); 


     // Show the list item if the phrase matches and increase the count by 1 
     } else { 
      $(this).show(); 
      count++; 
     } 
    }); 
+1

它的工作!你是传奇阿隆!谢谢! –