0

我正在尝试恢复标题与给定字符串匹配的任何书签文件夹的文件夹 ID 。

问题是当文本相同时它不会返回文件夹ID:C

这是我的代码:

chrome.bookmarks.getTree(function(bookmarks) 
{
  search_for_url(bookmarks, "herpaderp");
});


function search_for_title(bookmarks, title)
{
  for(i=0; i < bookmarks.length; i++)
  { 
    if(bookmarks[i].url != null && bookmarks[i].title == title)
    {
      // Totally found a folder that matches!
      return bookmarks[i].id;
    }
    else
    {
      if(bookmarks[i].children)
      {  
        // inception recursive stuff to get into the next layer of children
        return search_for_title(bookmarks[i].children, title);
      }
    }
  }

  // No results :C
  return false;
}
4

1 回答 1

1

search_for_title您的功能有两个问题。

  1. 变量i 必须是本地的。要使其成为局部变量,您必须使用var i = 0 而不是i = 0for语句中。

  2. search_for_titlefalse当找不到具有指定标题的书签时返回,但您仍需要查看下一项,因此在递归调用之后search_for_title只有找到书签时才return返回值。否则,应该继续搜索而不是返回。false

这是我测试正确运行的代码:

function search_for_title(bookmarks, title)
{
  for(var i=0; i < bookmarks.length; i++)
  { 
    if(bookmarks[i].url != null && bookmarks[i].title == title)
    {
      // Totally found a folder that matches!
      return bookmarks[i].id;
    }
    else
    {
      if(bookmarks[i].children)
      {  
        // inception recursive stuff to get into the next layer of children
        var id = search_for_title(bookmarks[i].children, title);
        if(id)
          return id;
      }
    }
  }

  // No results :C
  return false;
}
于 2012-12-19T09:52:44.983 回答