此示例代码应转储所有书签的列表。它在警报中不显示任何内容,但在正确关闭时填充列表。没有警报,它不会构建列表。由于chrome api函数都是异步的,除了超时之外还有“合法”的方法来解决这类问题吗?
<html>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.5.2/jquery.js"></script>
<body>
<script>
$(document).ready(function() {
var bookmarksList ='';
chrome.bookmarks.getTree(function(bookmarks) {
traverseBookmarks(bookmarks);
});
function traverseBookmarks(bookmarkTreeNodes) {
for(var i=0;i<bookmarkTreeNodes.length;i++) {
if(bookmarkTreeNodes[i].url) {
bookmarksList += '<li>Name: ' + bookmarkTreeNodes[i].title + ' ID: ' + bookmarkTreeNodes[i].id + ' URL: ' + bookmarkTreeNodes[i].url + ' Parent ID: ' + bookmarkTreeNodes[i].parentId;
}
if(bookmarkTreeNodes[i].children) {
traverseBookmarks(bookmarkTreeNodes[i].children);
}
}
}
alert(bookmarksList);
$('#list').html(bookmarksList);
});
</script>
<ul id="list"></ul>
</body>
</html>
答案 0 :(得分:3)
我不熟悉Chrome扩展程序API,但我猜测这是您正在寻找的内容:
$(function() {
function traverseBookmarks(nodes) {
var toReturn = [],
numNodes = nodes.length,
node;
for (var i = 0; i < numNodes; i++) {
node = nodes[i];
if (node.url) {
toReturn.push('<li>Name: ' + node.title + ' ID: ' + node.id + ' URL: ' + node.url + ' Parent ID: ' + node.parentId + '</li>');
}
if (node.children) toReturn.push(traverseBookmarks(node.children));
}
return toReturn.join('');
}
chrome.bookmarks.getTree(function(bookmarks) {
var bookmarksList = traverseBookmarks(bookmarks);
alert(bookmarksList);
$('#list').html(bookmarksList);
});
});
注意:
</li>
标记,我认为你错过了。答案 1 :(得分:1)
好的,如果我们是关于重构而且我们在Chrome中,它可以使用原生的Array.prototype.forEach函数和一个命名的匿名函数来获得更紧凑和清晰的代码......:P
$(function(){
chrome.bookmarks.getTree(function(bookmarks) {
var bookmarksList = [];
bookmarks.forEach(function me (node) {
if (node.url) {
bookmarksList.push('<li>Name: ' + node.title + ' ID: ' + node.id + ' URL: ' + node.url + ' Parent ID: ' + node.parentId + '</li>');
}
if (node.children) {
me(node.children);
}
});
$('#list').html(bookmarksList.join(''));
});
});
答案 2 :(得分:0)
我想你可以在$('#list').html(bookmarksList);
之后移动traverseBookmarks(bookmarks);
:
$(document).ready(function() {
var bookmarksList ='';
chrome.bookmarks.getTree(function(bookmarks) {
traverseBookmarks(bookmarks);
// ++++
$('#list').html(bookmarksList);
});
function traverseBookmarks(bookmarkTreeNodes) {
for(var i=0;i<bookmarkTreeNodes.length;i++) {
if(bookmarkTreeNodes[i].url) {
bookmarksList += '<li>Name: ' + bookmarkTreeNodes[i].title + ' ID: ' + bookmarkTreeNodes[i].id + ' URL: ' + bookmarkTreeNodes[i].url + ' Parent ID: ' + bookmarkTreeNodes[i].parentId;
}
if(bookmarkTreeNodes[i].children) {
traverseBookmarks(bookmarkTreeNodes[i].children);
}
}
}
});