Chrome 按标题查找现有书签文件夹?

bkhjykvo  于 2023-06-19  发布在  Go
关注(0)|答案(1)|浏览(121)

我正在尝试恢复任何书签文件夹的文件夹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;
}
zdwk9cvp

zdwk9cvp1#

search_for_title函数有两个问题。
1.变量i必须是本地变量。要使其成为局部变量,必须在for语句中使用vari = 0而不是i = 0

  1. search_for_title在找不到具有指定标题的书签时返回false,但您仍然需要查看下一项,所以递归调用search_for_title后,如果找到书签,则return返回值 only。否则,应该继续搜索,而不是返回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;
}

相关问题