如何在Javascript var索引中的文本中插入URL?

时间:2014-12-23 14:39:22

标签: javascript html

下面是脚本,目前它所做的是在你使用var搜索索引键入时创建一个下拉框,我想要完成的是能够在该下拉列表中点击google这个词并转到google.com,我知道这可以在html中使用  < a href =“google.com”>谷歌< / A>

我怎样才能在JS中完成这项工作?

<script> var searchIndex = ["google","apple","iPhone","ipad"];

var input = document.getElementById("searchBox"),
ul = document.getElementById("searchResults"),
inputTerms, termsArray, prefix, terms, results, sortedResults;


var search = function() {
inputTerms = input.value.toLowerCase();
results = [];
termsArray = inputTerms.split(' ');
prefix = termsArray.length === 1 ? '' : termsArray.slice(0, -1).join(' ') + ' ';
terms = termsArray[termsArray.length -1].toLowerCase();

 for (var i = 0; i < searchIndex.length; i++) {
 var a = searchIndex[i].toLowerCase(),
    t = a.indexOf(terms);

 if (t > -1) {
  results.push(a);
 }
 }

evaluateResults();
};

  var evaluateResults = function() {
  if (results.length > 0 && inputTerms.length > 0 && terms.length !== 0) {
    sortedResults = results.sort(sortResults);
  appendResults();
  } 
  else if (inputTerms.length > 0 && terms.length !== 0) {
   ul.innerHTML = '<li> <strong>' 
   + inputTerms 
   + '</strong> is not a valid part number  <br><small><a ></li>';

   }
   else if (inputTerms.length !== 0 && terms.length === 0) {
   return;
   }
   else {
   clearResults();
  }
  };

 var sortResults = function (a,b) {
 if (a.indexOf(terms) < b.indexOf(terms)) return -1;
 if (a.indexOf(terms) > b.indexOf(terms)) return 1;
 return 0;
 }
    var appendResults = function () {
  clearResults();

  for (var i=0; i < sortedResults.length && i < 5; i++) {
   var li = document.createElement("li"),
    result = prefix 
      + sortedResults[i].toLowerCase().replace(terms, '<strong>' 
      + terms 
      +'</strong>');

        li.innerHTML = result;
   ul.appendChild(li);
  }

   if ( ul.className !== "term-list") {
    ul.className = "term-list";
   }
    };

     var clearResults = function() {
    ul.className = "term-list hidden";
    ul.innerHTML = '';   
   };

      input.addEventListener("keyup", search, false);

     </script>

1 个答案:

答案 0 :(得分:1)

你可以这样做:

var terms = document.getElementsByClassName('term-list');
for (var i = 0; i<terms.length;i++) {
terms[i].addEventListener('click',gothere);
}
function gothere () {
 console.log(this.textContent);  
    var b = 'http://www.'+this.textContent+'.com';
    console.log(b);  // replace this with the next line:
  //  window.location.href = b;
}

DEMO