我正在尝试为我创建的数据集构建一个简单的搜索界面。
我已遵循Lunr guides创建了索引。我在网页上放置一个输入框,以获取用户键入的搜索值,然后针对索引运行该值。
当我运行console.log(results[0])
时-我很高兴在控制台中得到正确的结果:
当我尝试使“法律和法规合规性”显示在我的网页上时,问题就来了。发生两件事:
当我尝试将console.log(results[0].ref)
输出到控制台时,程序冻结,无法再键入。
当我尝试将document.getElementById("demo").innerHTML= results[0]
输出到网页时,我得到了[object object]-这很令人惊讶,因为控制台行提供了与该对象关联的实际数据。
var documents = [{
"TooltipInfo": "administration - administration general: 2 years 5 years de: ",
"Category": "None1",
},
{
"TooltipInfo": "administration - appointment books, diaries, desk calendars: 1 years 0 years de: ",
"Category": "None2",
},
{
"TooltipInfo": "administration - correspondance day files: 1 years 0 years de: ",
"Category": "None3",
},
{
"TooltipInfo": "legislation and directives - general: 2 years 0 years de: ",
"Category": "Legal & Legislative Compliance",
}
]
var idx = lunr(function() {
this.ref('Category')
this.field('TooltipInfo')
documents.forEach(function(doc) {
this.add(doc)
}, this)
})
var searchInput = document.querySelector('#search-input')
searchInput.addEventListener('keyup', function() {
var results = idx.search(searchInput.value)
// console.log(results[0].ref)
// var results2 = results.forEach(function(item){return item})
document.getElementById("demo").innerHTML = results[0]
})
<script src="https://unpkg.com/lunr/lunr.js"></script>
<input type="search" id="search-input" placeholder="Search">
<p id="demo"></p>
如何使搜索结果显示在我的网页上?
答案 0 :(得分:1)
您应该为innerHTML
使用一个值。 results[0]
是一个对象。所以应该是document.getElementById("demo").innerHTML = results[0].ref
var documents = [{
"TooltipInfo": "administration - administration general: 2 years 5 years de: ",
"Category": "None1",
},
{
"TooltipInfo": "administration - appointment books, diaries, desk calendars: 1 years 0 years de: ",
"Category": "None2",
},
{
"TooltipInfo": "administration - correspondance day files: 1 years 0 years de: ",
"Category": "None3",
},
{
"TooltipInfo": "legislation and directives - general: 2 years 0 years de: ",
"Category": "Legal & Legislative Compliance",
}
]
var idx = lunr(function() {
this.ref('Category')
this.field('TooltipInfo')
documents.forEach(function(doc) {
this.add(doc)
}, this)
})
var searchInput = document.querySelector('#search-input')
searchInput.addEventListener('keyup', function() {
var results = idx.search(searchInput.value)
//console.log(results[0])
// var results2 = results.forEach(function(item){return item})
document.getElementById("demo").innerHTML = results[0].ref;
})
<script src="https://unpkg.com/lunr/lunr.js"></script>
<input type="search" id="search-input" placeholder="Search">
<p id="demo"></p>