문제

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.

다른 팁

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

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);
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top