0

我正在尝试为我创建的数据集构建一个简单的搜索界面。

我已按照 Lunr指南创建索引。我在我的网页上放置了一个输入框,用于获取用户输入的搜索值,然后针对索引运行该值。

当我运行时console.log(results[0])- 我很高兴在控制台中得到正确的结果:

控制台中一行的屏幕截图:object {ref:

当我试图让“法律和法规遵从性”出现在我的网页上时,问题就来了。发生两件事:

当我尝试输出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>

如何让搜索结果显示在我的网页上?

4

1 回答 1

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>

于 2019-07-23T12:35:18.160 回答