0

我正在开发一个待办事项列表应用程序,用户可以在其中将待办事项列表项添加到网页,还可以搜索待办事项列表项。下面我正在研究搜索功能。现在发生的事情是,我在页面上添加了一个 li 项目,上面写着“你找到了”+ 用户在下面搜索的名称 + 与该特定项目匹配的任务。但是,我不确定如何匹配使用该名称的每个列表项。例如,我可以让一个叫 Bob 的人做三项不同的任务。现在这个搜索只会匹配第一个,但我想匹配所有三个。有什么建议么?

function search() {
   var searchTerm = document.getElementById("search").value;
   searchTerm = searchTerm.trim();

   if(searchTerm == null || searchTerm == "") {
   alert("Please enter a string to search for");
   return;
   }
   else {
     var todoObj = undefined;
     results = undefined;
     re = undefined;

   for(var i = 0; i < todos.length; i++) {
     todoObj = todos[i];
     re = new RegExp(searchTerm, "ig");
     resultsOne = todoObj.who.match(re);
     if(resultsOne) {
       var ul = document.getElementById("test");
       var li = document.createElement(li);
       li.className = "listItem";  
       li.innerHTML = "You found " + todoObj.who + " who needs to " + todoObj.task; 
       ul.appendChild(li);    
       }
      }      
     }    
    }
4

1 回答 1

1

保留匹配的待办事项的临时列表,最后,在最后,输出您的结果:

var matchedTodos = []; // temporary list of matched todos

for(var i = 0; i < todos.length; i++) {
     todoObj = todos[i];
     re = new RegExp(searchTerm, "ig");
     resultsOne = todoObj.who.match(re);
     if(resultsOne) {
         // found a match, add it to our temporary list
         matchedTodos.push(todoObj);
     }
 } 

// now output the matched todos

if (matchedTodos.length > 0) {
    var ul = document.getElementById("test");
    var li = document.createElement("li");
    li.className = "listItem";  
    var tasks = '';
    var todoObj = null;
    for(var j = 0; j < matchedTodos.length; j++) {
        todoObj = matchedTodos[j];
        tasks += todoObj.task + ', ';
    }
    li.innerHTML = "You found " + todoObj.who + " who needs to " + tasks; 
    ul.appendChild(li);  
}

您希望输出类似于"You found Bob who needs to clean his room, take a bath, sleep". 您将不得不添加一些逻辑以获得正确数量的,逗号以使句子正确:P

编辑:将它们全部作为单独的列表项:

var matchedTodos = []; // temporary list of matched todos

for(var i = 0; i < todos.length; i++) {
     todoObj = todos[i];
     re = new RegExp(searchTerm, "ig");
     resultsOne = todoObj.who.match(re);
     if(resultsOne) {
         // found a match, add it to our temporary list
         matchedTodos.push(todoObj);
     }
 } 

// now output the matched todos

if (matchedTodos.length > 0) {
    var ul = document.getElementById("test");
    var todoObj = null;
    for(var j = 0; j < matchedTodos.length; j++) {
        var li = document.createElement("li");
        li.className = "listItem";  
        todoObj = matchedTodos[j];
        li.innerHTML = "You found " + todoObj.who + " who needs to " + todoObj.task;
        ul.appendChild(li);  
    } 
}
于 2013-03-08T20:28:12.657 回答