将按钮插入到内容脚本的 DOM 中
我正在编写一个 Firefox 扩展,但遇到以下问题:
我在内容脚本 (insertInDom.js) 中添加了一个按钮
$('#leftCol').append("<input type='button' value='Check Privacy' onclick=\"buttonClick()\" >");
用户单击该按钮后,应该启动内容脚本中的一个函数,但我总是得到 错误 Fehler:buttonClick 未定义
我如何对脚本中插入按钮的事件做出反应?谢谢:)
整个相关代码:
main.js
var pageMod = require("page-mod");
pageMod.PageMod({
include: ["http://www.facebook.com/"],
contentScriptWhen: 'ready',
contentScriptFile: [data.url('jquery-1.6.4.js'),
data.url('insertInDom.js')],
onAttach: function(worker) {
worker.port.on('buttonClicked', function(content) {
console.log(content);
});
}
});
insertInDom.js:
function buttonClick(){
self.port.emit("buttonClicked", "true");
}
$('#leftCol').append("<input type='button' value='Check Privacy' onclick=\"buttonClick()\" >");
I'm writing a firefox extension and have the following problem:
I added inside a content script (insertInDom.js) a Button
$('#leftCol').append("<input type='button' value='Check Privacy' onclick=\"buttonClick()\" >");
After the user clicked the button a function from the content script should be started, but I always get the error Fehler: buttonClick is not defined
how can I react on the event of an inserted Button inside my script? Thank you :)
The whole relevant code:
main.js
var pageMod = require("page-mod");
pageMod.PageMod({
include: ["http://www.facebook.com/"],
contentScriptWhen: 'ready',
contentScriptFile: [data.url('jquery-1.6.4.js'),
data.url('insertInDom.js')],
onAttach: function(worker) {
worker.port.on('buttonClicked', function(content) {
console.log(content);
});
}
});
insertInDom.js:
function buttonClick(){
self.port.emit("buttonClicked", "true");
}
$('#leftCol').append("<input type='button' value='Check Privacy' onclick=\"buttonClick()\" >");
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
从 jQuery 1.7 开始,我认为添加单击事件的适当方法(甚至添加到加载初始页面后创建的 DOM 元素)如下所示:
docs: http://api.jquery.com/on/
因此,您可以尝试在输入中添加 ID,然后执行以下操作:
As of jQuery 1.7, I think the appropriate way to add a click event (even to a DOM element that has been created after the initial page is loaded is like so:
docs: http://api.jquery.com/on/
So, you could try adding an ID to your input and then something like:
既然您已经在使用 jQuery,为什么不使用 jQuery 来处理您的点击事件呢?另外,我尝试养成使用 jQuery 构建 DOM 元素的习惯 - 它将确保您不会偶然发现一些不太可能的浏览器问题。
Since you're already using jQuery, why not make use of jQuery to handle your click event? Also, I try to make a habit of using jQuery to build DOM elements - it will make sure you don't stumble upon some unlikely browser issues.