Greasemonkey 脚本中未触发 jQuery 单击事件
我已通过 GM 将图像附加到页面,并且尝试执行单击事件但无济于事。
我有什么想法吗?
页面标记包含:
<img id="kwdHelp" src="myImage />
Greasemonkey/Tampermonkey 脚本片段...
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();}
jQueryLoaded();
};
checkIfjQLoaded();
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();}
jQueryLoaded();
};
checkIfjQLoaded();
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
当您尝试将事件绑定到该元素时,该元素是否存在于文档中?
我自己经常犯这样的错误。
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.
假设这两个未定义的函数确实在代码中的某处,问题中的代码应该可以工作(尽管需要改进,请参见下文)。
问题中没有的东西就是有问题的。
摆脱那个
checkIfjQLoaded()
胡言乱语。这是过时且糟糕的做法。使用
// @require
加载 jQuery,默认情况下脚本会在document.ready
处触发。代码不仅更简单,而且更快、更高效,因为它不必每次都获取 jQuery。
该脚本将变为:
最后,如果您想在 Chrome 上使用该脚本,请安装Tampermonkey< /a> 以获得最佳结果。
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.
Get rid of that
checkIfjQLoaded()
malarkey. It's obsolete and poor practice.Use
// @require
to load jQuery, and the script fires atdocument.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:
Finally, if you want to use the script on Chrome, install Tampermonkey for best results.