开发者

GreaseMonkey onclick binding

开发者 https://www.devze.com 2022-12-10 23:37 出处:网络
When I write a GreaseMonkey script, if I create a div and set onclick to alert it works: var btn = document.createElement(\'div\');

When I write a GreaseMonkey script, if I create a div and set onclick to alert it works:

var btn = document.createElement('div'); btn.setAttribute('onclick',"alert('clicked!');");

However, if I ask it to do something else that was defined ear开发者_运维问答lier then it fails:

function graphIt() {...}; var btn = document.createElement('div'); btn.setAttribute('onclick',"graphIt();");

Is there any way I can bind a function to the onclick event of a div?


Your problem is that since you're seting the attribute to a string, it's evaluating the string in the context of the page itself, which doesn't have a graphIt function.

You should call the addEventListener method, like this:

function graphIt() {...}; var btn = document.createElement('div'); 
btn.addEventListener("click", graphIt, false);
0

精彩评论

暂无评论...
验证码 换一张
取 消