简体   繁体   English

我无法让我的JavaScript事件监听器正常工作

[英]I can't get my JavaScript eventlistener to work properly

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. 无论我如何尝试,都无法触发链接上的click eventlistener。 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,因为该代码对页面上的代码不可用。

dropit = function (e) {
  e.preventDefault();
  alert(e.target.textContent);
}

document.getElementById('newlink').addEventListener('click',
         function (e){
                   return function (){
                     dropit(e);
                   }
                 }(),false);

You have to have your Greasemonkey script write the code into a new <script> tag in the page. 你必须有你的Greasemonkey脚本编写的代码到一个新<script>在页面标签。 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. 至少,这是我所知道的唯一方法。

e must be passed into second function inside addEventListener, not first. 必须将e传递给addEventListener内的第二个函数,而不是第一个。 Like this: 像这样:

dropit = function (e) {
  e.preventDefault();
  alert(e.target.textContent);
}

document.getElementById('newlink').addEventListener('click',
         function (e){
                   return function (e){
                     dropit(e);
                   }
                 }(e),false);
<a id='mylink' href='http://www.google.com'>google</a> the link 

<script src="http://yui.yahooapis.com/3.0.0/build/yui/yui-min.js"></script>
<script>
YUI().use('event', function(Y){

  Y.one('#mylink').on('click', function(e){
    e.halt();
    alert(this.get('href'));  
  });
}); 
</script>

here is the non YUI version 这是非YUI版本

<a id='mylink' href='#'>google</a> the link 

<script>

(function(){
  var dropit = function (e) {
    e.preventDefault();
    alert(e.target.textContent);
  }

  document.getElementById('mylink').addEventListener('click', dropit, false);
}());
</script>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM