我无法让我的 JavaScript 事件监听器正常工作
这让我很困惑,我尝试了很多不同的方法,但我无法让它发挥作用。 有人可以帮忙吗?无论我如何尝试,我都无法让链接上的单击事件侦听器触发。该代码位于greasemonkey 脚本中。我相信我必须使用闭包方法才能引用 Greasemonkey 脚本中的函数 dropit,因为它不可用于页面上的代码。
dropit = function (e) {
e.preventDefault();
alert(e.target.textContent);
}
document.getElementById('newlink').addEventListener('click',
function (e){
return function (){
dropit(e);
}
}(),false);
This has got me stumped, I've tried lots of different things, but I can't get this to work.
Can anyone help? No matter what I try I can't get the click eventlistener on the link to fire. The code is in a greasemonkey script. I believe I have to use the closure method to be able to refer to the function dropit in the greasemonkey script, as it is not available to the code on the page.
dropit = function (e) {
e.preventDefault();
alert(e.target.textContent);
}
document.getElementById('newlink').addEventListener('click',
function (e){
return function (){
dropit(e);
}
}(),false);
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您必须让 Greasemonkey 脚本将代码写入到页面中的新
标记中。完成后,您的页内事件处理程序设置就可以正常进行。至少,这是我所知道的唯一方法。
You have to have your Greasemonkey script write the code into a new
<script>
tag in the page. Once that's done, then your in-page event handler setup can proceed as normally. At least, that's the only way I've ever known to do it.这是非 YUI 版本
here is the non YUI version
e
必须传递到 addEventListener 内的第二个函数,而不是第一个函数。像这样:
e
must be passed into second function inside addEventListener, not first.Like this: