这里需要延迟执行 jQuery 吗?
此示例代码应转储所有书签的列表。它在警报中不显示任何内容,但在关闭时正确填充列表。如果没有警报,它就不会构建列表。由于 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>
This sample code should dump a list of all bookmarks. It shows nothing in the alert but populates the list on close correctly. Without the alert, it doesn't build the list. Since chrome api functions are all asynchronous is there a "legit" way to solve this type of problem other than a timeout?
<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>
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
我不熟悉 Chrome 扩展 API,但我猜测这就是您正在寻找的:
注意:
标签,我认为您错过了。
I'm not familiar with the Chrome extension API, but I'd hazard a guess that this is what you're looking for:
Notes:
</li>
tag, which I think you missed.好吧,如果我们要进行重构并且在 Chrome 中,则可以使用本机 Array.prototype.forEach 函数和命名匿名函数来获得更紧凑和清晰的代码...:P
Ok, if we are about refactoring and we are in Chrome it can be used the native Array.prototype.forEach function and a named anonymous function for a more compact and clear code... :P
我想你可以将
$('#list').html(bookmarksList);
移到traverseBookmarks(bookmarks);
之后,如下所示:I suppose you can move
$('#list').html(bookmarksList);
aftertraverseBookmarks(bookmarks);
like so: