English 中文(简体)
GreaseMonkey onclick binding
原标题:

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 earlier 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);
问题回答

暂无回答




相关问题
Call href from JavaScript

This is the same question as THIS ONE, I can t answer that anymore, so I m re-posting it with my account. Sorry for the mess. I need a Greasemonkey script that on a page load activates a href link ...

form.submit() causes uncaught exception in greasemonkey

I m using a greasemonkey script to load a page with ajax and automatically fill in the form fields inside the page and submit the form. The problem is that when the form.submit() statement is executed ...

Can I build an addin for Gmail?

Is there a way I can create an addin for my Gmail account? Is GreaseMonkey the only real way? I use Gmail for customer service, and I d like to create a tool that looks up the customer and preps a ...

Is nested XMLHttpRequests with multiple closures a good idea?

I have a Greasemonkey script which operates on a search results page at a video site. The function of the script is to take a javascript link that opens a new window with a flash player, jump through ...

jQuery data() function in GreaseMonkey

I m trying to use jQuery s data() function to store and retrieve data on an element. I want to retrieve the data stored in a textarea whenever the user enters the space bar1. However, everytime I do ...

GreaseMonkey onclick binding

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 ...

热门标签