2013-06-27 24 views
0

我試圖隱藏所有<li>元素,然後僅顯示那些包含孩子<p><li>,其中的文本與輸入/搜索字段的值匹配。如何使用過濾器顯示輸入值?

HTML:

<input id="search" type="text" placeholder="Search"> 

<ul class="items"> 

    <li class="item"> 
     <p class="keywords" style="display: none;">skins, hair</p>//keywords 
     <a class="thumb" href="#"><img src="koalahat.jpg"></a> 
    </li> 

    <li class="item"> 
     <p class="keywords" style="display: none;">hair</p> 
     <a class="thumb" href="#"><img src="goosehat.jpg"></a> 
    </li> 

</ul> 


JS:

$('#search').keyup(function(){ 
    var typed = $(this).val(); //get the input field value 
    $('.items li').hide() //hide all LIs... 
    $('.items li').filter(function(){ //filter all LIs that... 
     $('.items li p.keywords:contains(typed)').parent().show(); //... that contain the typed keywords, and show them. 
    }); 
    console.log(typed); 
}) 

我想不通爲什麼改變$('.items li p.keywords:contains(typed)')$('.items li p.keywords:contains("skins")')回報所需的輸出,前者沒有。

回答

0

字符串串聯問題。試試這個:

$('p.keywords:contains("' + typed + '")', this).parent().show(); 

我認爲,所有你需要的是:

$('#search').keyup(function() { 
    var typed = this.value; //get the input field value 
    $('.items li').hide() //hide all LIs... 
    $('.items li').find('p.keywords:contains("' + typed + '")', this).parent().show(); 
    console.log(typed); 
}) 

Fiddle

雖然問題是,在選擇$('.items li p.keywords:contains(typed)')類型化被認爲是一個字符串,而不是變量所以它的價值不被評估。相反,你應該連接變量和字符串。而且你可以取消過濾器,只要選擇器就足夠了。

相關問題