JQuery搜索过滤器代码我错过了什么步骤?

时间:2016-10-09 07:03:03

标签: jquery html

我已将教程中的步骤应用到我自己的搜索栏中以获取照片库。目的是让搜索栏实时过滤图像,并显示与图库中搜索栏中描述的图像相匹配的图像。第一部分代码可以工作(当写入搜索栏时,库会隐藏)但其余部分尚未存在。我的html是用<a>标签构建的,在教程中他们没有。我试过在JQuery代码中添加这些,但没有运气。有谁知道我在哪里出错?

<div id="photo-container" class="data-list">
     <ul>
        <li data-keywords="dry hill"><a href="Photos/01.jpg"><img     src="Photos/Thumbnails/01.jpg" alt="Photo of a dry hill with blue skys.  This image was captured at the end of Summer in the region of Hawkes Bay." title="Dry Hill" class="photo photo1">
               </a></li>
             <li data-keywords="lake blue sky"><a href="Photos/02.jpg"><img src="Photos/Thumbnails/02.jpg" alt="Photo of a lake with blue sky.  This image was taken in the mid morning of the Lakes District. " title="Lake" class="photo">
                 </a></li>
             <li data-keywords="green fields"><a href="Photos/03.jpg"><img src="Photos/Thumbnails/03.jpg" alt="Green Fields is an image captured in the lush Southland area. " title="Photo Three" class="Green Fields">
                 </a></li>

     </ul>
    </div><!--closing photo-container-->

Jquery代码

$(document).ready(function(){

$("#search").keyup(function(){

var current_query = $("#search").val();

if(current_query != ""){
 $("#photo-container").hide();

 $("#photo-container li").each(function(){

     var current_keyword = $(this).attr("data-keywords");

    if (current_keyword.indexOf(current_query) >=0) {
        $(this).show();
    } 
      });
} else {
        $("#photo-container li").show();
    }




 });  

});

1 个答案:

答案 0 :(得分:0)

您的代码正在查找所有<a>元素并查找其“数据关键字”属性,但“数据关键字”属性位于<li>元素上。

中的css选择器中删除<a>
$("#photo-container li a").each(function(){

或将'data-keywords'标签移至<li>元素。