简体   繁体   中英

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

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.

e must be passed into second function inside addEventListener, not first. 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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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