简体   繁体   中英

Some problems with Javascript functions and this argument

I am using colorbox to my popups and...

This works fine.

$(".show_popup").colorbox({inline:true, width:"800px", onOpen: function() {
   type = $(this).attr('type);
   ....
}

But I want use my inner function many times so I want make it a module function.

});

(function ($,a) {
 var p = {
   showPopup: function (popup_type) { 
    ...
   },

   bindEvents: function () {
       $(".show_popup").colorbox({inline:true, width:"800px", onOpen: p.showPopup($(this).attr('type')) }); 
   }
...
}
a.Popups = p;
})(jQuery);

But this don't work - it is problem with $(this) - and function execute only once after page loading.

(function ($,a) {
  var p = {
   showPopup: function (popup_type) { 
    ...
   },

   bindEvents: function () {
       $(".show_popup").colorbox({inline:true, width:"800px", onOpen: p.showPopup }); 
   }
...
}
a.Popups = p;

})(jQuery);

And this don't work of course too, but execute many times. So can you help me know what is matter?

The problem with onOpen: p.showPopup($(this).attr('type)) is that it will run the p.showPopup-function at the moment that you bind it to onOpen. What you want is that it runs at the moment the onOpen-event is triggered. Use

onOpen: function() { p.showPopup($(this).attr('type')); }

instead

(edit) assuming that p.showPopup is defined, I can't see it in your code.

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