popup.html中的Jquery和异步方法



我在玩构建chrome扩展。当您单击工具栏中的图标时,我目前正在测试popup.html功能。

然而,我很难将jquery与chrome.*api的异步方法结合使用。也许有人可以为我做进一步的阐述?

场景

popup.html包含与当前选项卡交互的按钮,按钮的href是基于当前选项卡的url+数组中的其他文本生成的。使用jQuery,我有一个$("button").click();文档内部已准备就绪。然而,这两人似乎打得并不好。除了jQuery以外的所有东西都可以工作。

例如。

var the_current_url = '';
var url_addition = {
"button 1" : "/home",
"button 2" : "/about",
"button 3" : "/content"
}
function getCurrentURL(currentURL) {
if(currentURL) {
var scheme = currentURL.match(/^https?:///i);
var newURL = '';
currentURL = currentURL.substring( scheme[0].length, currentURL.length );
currentURL = currentURL.substring( 0, currentURL.indexOf("/") );
the_current_url = newURL.concat(scheme[0], currentURL);
}
return true;
}
function buildButtons() {
var new_code = "<ul>n";
// Generate the <li>
for (var key in url_addition) {
new_code = new_code.concat("<li><a href="",
the_current_url.concat(url_addition[key]),
"" title="",
url_addition[key],
"">",
key,
"</a></li>n");
}
new_code = new_code.concat("</ul>");

return new_code;
}
// Get the Current URL and build the new url
chrome.tabs.query({
'active': true
}, function(tab) {
var currentURL = tab[0].url;
// Pass the Current URL to bb_current_url via Function
getCurrentURL(currentURL);
// add the popup buttons
document.getElementById("button-container").innerHTML = buildButtons();
});

$(document).ready(function() {
// Clicked on buttons
$("a").parents("#button-container").click(function() {
console.log("test" );
});
});

我可以获得当前选项卡的url,并使用适当的链接构建按钮,但是当涉及到jquery点击操作时,它不起作用。jquery的事情似乎发生在按钮容器的按钮创建之前。这样$("a")的点击就不会向console.log返回任何输出。有人知道我在这个例子中应该如何正确地将chrome的api与jquery一起使用吗?

这与jQuery无关——普通JS也会出现同样的问题
基本上,您需要确保:

  1. 只有当准备就绪时,链接才会插入到DOM中(因此您的按钮容器存在)。

  2. 在链接插入DOM后,行为被附加到链接上。

您可以更改代码,以便将链接插入$(document).ready(...)内部(以确保按钮容器已经存在),并在插入链接后立即注册事件处理程序(以确保链接存在于DOM中)
例如:

/* Original comments omitted for brevity */
$(document).ready(function () {
/* The DOM is ready, so `#button-container` is guaranteed to be present */
chrome.tabs.query({ active: true } , function (tabs) {
var currentURL = tabs[0].url;
getCurrentURL(currentURL);
$('#button-container').html(buildButtons());
/* Place this inside the callback to ensure the links are present */
$('a').parents('#button-container').click(function() {
console.log('test');
});
});
});

BTW,您的$('a').parents('#button-container')将解析为#button-container(而不是对子级a)。如果我没有错的话,您希望针对#button-container内部的所有a,而不是#button-container本身
要实现此目的,请将您的表达式更改为:

$('#button-container a').click(function () {...});

最新更新