我不得不使用jQuery,我没有写,它包含在模板中。
有一个函数可以执行'猜测类型',并使用主导航作为要搜索的数据。在您键入时,站点中的页面会出现在下拉列表中。
我需要从数据库中下载客户名称,但我似乎无法使该功能正常工作。
function searchInNav(s)
{
// Split keywords
var keywords = s.toLowerCase().split(/\s+/);
var nbKeywords = keywords.length;
// Search links
//var links = $('nav a'); // original
var links = [];
// LOAD CUSTOMERS AND EVENTS
$.post('includes/ajax/global.php', { list: 'search', text: keywords },
function(data){
alert(data);
links.push($(data));
},
"html"
);
var matches = [];
links.each(function(i)
{
var text = $(this).text().toLowerCase();
var textMatch = true;
for (var i = 0; i < nbKeywords; ++i)
{
if (text.indexOf(keywords[i]) == -1)
{
textMatch = false;
break;
}
}
if (textMatch)
{
// All keywords found
matches.push(this);
}
});
// Build results list
var nbMatches = matches.length;
if (nbMatches > 0)
{
var output = '<p class="results-count"><strong>'+nbMatches+'</strong> match'+((nbMatches > 1) ? 'es' : '')+'</p>';
output += '<ul class="small-files-list icon-html">';
for (var m = 0; m < nbMatches; ++m)
{
// Text with highlighted keywords
var link = $(matches[m]);
var text = link.text();
var path = [text];
for (var i = 0; i < nbKeywords; ++i)
{
text = text.replace(new RegExp('('+keywords[i]+')', 'gi'), '<strong>$1</strong>');
}
// Path
var parent = link;
while ((parent = parent.parent().parent().prev('a')) && parent.length > 0)
{
path.push(parent.text());
}
output += '<li><a href="'+matches[m].href+'">'+text+'<br><small>'+path.reverse().join(' > ')+'</small></a></li>';
}
return output+'</ul>';
}
else
{
return '<p class="results-count">'+settings.messageNoMatches+'</p>';
}
};
我一直在使用links.each行得到错误,说对象没有方法。
我需要修理什么?
谢谢!
答案 0 :(得分:0)
这是你的问题:
//var links = $('nav a'); // original
$('nav a')在nav中生成所有标签的jQuery对象。你的只是一个阵列。
您需要修改整个循环以将其作为数组处理而不是jquery对象...
for(var i = 0; i < links.length; i ++)
{
var text = links[i].toLowerCase();
var textMatch = true;
for (var n = 0; n < nbKeywords; ++n)
{
if (text.indexOf(keywords[n]) == -n)
{
textMatch = false;
break;
}
}
if (textMatch)
{
// All keywords found
matches.push(links[i]);
}
});
但我无法猜测上述修改。一般的概念是你将它从jquery对象更改为数组,因此你必须相应地修改循环。
另外,这是什么:
links.push($(data));
数据是否返回预期的dom id?喜欢#some_div?否则$()毫无意义。它应该只是数据。