我有一个用于输入文本的文本字段。通过使用该文本,我需要从div中过滤数据。 div包含大约100个值列表(<li>..</li>
)。
如果文本在div中匹配,那么我可以更改该li元素的背景。
但问题是,如果匹配的文本是div中的最后一个元素,那么我需要手动向下滑动div,但我的要求是将div自动滑动到匹配的元素位置。 例如,
var array = [
"First Element","Second Element","Third Element","Fourth Element",
"Fifth Element","Sixth Element","Seventh Element",
"Eighth Element","Ninth Element","Tenth Element",
"Eleventh Element","Twelth Element","Thirteen Element",
"Fourteen Element","Fifteen Element","Sixteen Element",
"Seventeen Element","Eighteen Element","Ninteen Element",
"Twenty Element","Twenty one Element",
"Twenty two Element","Twenty three Element","Twenty Fouth Element",
"Twenty Fifth Element","Twenty Sixth Element","Twenty Seventh Element",
"Twenty Eighth Element","Twenty Ninth Element"
];
$("#filter").keyup(function()
{
var typedText = $(this).val();
$("#list").find("li").css({'background-color': 'transparent'});
$.each(array, function(id,obj)
{
if(obj.toLowerCase().indexOf(typedText.toLowerCase()) != -1)
{
$("#list").find("li:contains(" + typedText + ")").css({'background-color': '#ccc'});
}
})
})
我尝试了很多但无法达到解决方案。任何建议都会受到赞赏。
答案 0 :(得分:0)
很难理解你需要什么。但也许这是这样的?
http://jsfiddle.net/6ufmdgyw/或http://jsfiddle.net/6ufmdgyw/1/
使用:eq选择器选择正确匹配的元素。
$("#filter").keyup(function()
{
var typedText = $(this).val();
$("#list").find("li").css({'background-color': 'transparent'});
$.each(array, function(id,obj)
{
if(obj.toLowerCase().indexOf(typedText.toLowerCase()) != -1)
{
$("#list").find("li:eq("+id+")").slideDown();
} else {
$("#list").find("li:eq("+id+")").slideUp();
}
})
})
密钥为.find("li:eq("+id+")")
答案 1 :(得分:0)
我已经更新了@Kharchi给出的JS Fiddle的代码。希望这符合您的要求。
var array = [
"First Element","Second Element","Third Element","Fourth Element",
"Fifth Element","Sixth Element","Seventh Element",
"Eighth Element","Ninth Element","Tenth Element",
"Eleventh Element","Twelth Element","Thirteen Element",
"Fourteen Element","Fifteen Element","Sixteen Element",
"Seventeen Element","Eighteen Element","Ninteen Element",
"Twenty Element","Twenty one Element",
"Twenty two Element","Twenty three Element","Twenty Fouth Element",
"Twenty Fifth Element","Twenty Sixth Element","Twenty Seventh Element",
"Twenty Eighth Element","Twenty Ninth Element"
];
$.each(array, function(c,e) {
$('#list').append('<li>'+e+'</li>');
});
$("#filter").keyup(function()
{
offsetStart = true;
var typedText = $(this).val();
$("#list").find("li").css({'background-color': 'transparent'});
$.each(array, function(id,obj)
{
if(obj.toLowerCase().indexOf(typedText.toLowerCase()) != -1)
{
$("#list").find("li:eq("+id+")").css({'background-color': '#ccc'})
if(offsetStart){
tempOffset = $("#list").find("li:eq("+id+")").offset().top;
$(window).scrollTop( tempOffset );
offsetStart = false;
}
}
})
})