jQuery click event not firing in Greasemonkey script
I've appended an image to a page via GM and I'm trying to execute a click event to no avail.
Any ideas what I'm missing?
Page markup contains:
<img id="kwdHelp" src="myImage />
Greasemonkey/Tampermonkey script snippet...
function jQueryLoaded(){
jQuery('#kwdHelp').click(function(){
alert('clicked show help'); //DOES NOT FIRE
});
jQuery(document).bind('DOMNodeInserted', function(event)
{
if (event && event.target && jQuery(event.target).attr("class") == 'aw-ti-resultsPanel-details')
{
if (waitToLoad !== null)
{
window.clearTimeout(waitToLoad);
}
waitToLoad = window.setTimeout(SearchDomains, 100);
}
});
setupLoadingImage();
};
function checkIfjQLoaded() {
//if(typeof unsafeWindow.jQuery == 'undefined') { window.setTimeout(checkIfjQLoaded,100); }
//else { jQuery = unsafeWindow.jQuery; jQueryLoaded();}
jQueryLoade开发者_如何学JAVAd();
};
checkIfjQLoaded();
Is the element present in the document at the time when you try to bind the event to it?
I usually do that mistake myself.
The code in the question should work (although it needs improvement, see below), assuming that the 2 undefined functions are really in the code somewhere.
Something that is not in the question is at fault.
- Link to the target page.
- Show the full, unedited code.
- What error messages does the Firebug console give?
Get rid of that checkIfjQLoaded()
malarkey. It's obsolete and poor practice.
Use // @require
to load jQuery, and the script fires at document.ready
by default.
Not only is the code simpler but it is much faster and more efficient, as it doesn't have to fetch jQuery every time.
The script would become:
// ==UserScript==
// @name _YOUR_NAME
// @include http://YOUR_SERVER/YOUR_PATH/*
// @require http://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js
// ==/UserScript==
$('#kwdHelp').click(function(){
alert('clicked show help'); //DOES NOT FIRE
});
$(document).bind('DOMNodeInserted', function(event)
{
if (event && event.target && $(event.target).attr("class") == 'aw-ti-resultsPanel-details')
{
if (waitToLoad !== null)
{
window.clearTimeout(waitToLoad);
}
waitToLoad = window.setTimeout(SearchDomains, 100);
}
});
setupLoadingImage();
function SearchDomains () {
//...
}
function setupLoadingImage () {
//...
}
Finally, if you want to use the script on Chrome, install Tampermonkey for best results.
精彩评论