【问题标题】:Some problems with Javascript functions and this argumentJavascript函数和这个参数的一些问题
【发布时间】:2013-11-13 20:00:32
【问题描述】:

我正在对我的弹出窗口使用颜色框...

这很好用。

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

但是我想多次使用我的内部函数,所以我想把它变成一个模块函数。

});

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

但这不起作用 - 这是$(this) 的问题 - 并且函数仅在页面加载后执行一次。

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

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

})(jQuery);

当然这也不起作用,但要执行很多次。那么你能帮我知道什么是问题吗?

【问题讨论】:

  • 不清楚您在做什么或您的问题是什么。请在 jsbin.com 等服务上制作样本,并仅包含与您的问题相关的内容。这让人们更容易为您提供帮助。
  • bfavaretto,我已经让我的代码更完整了。抱歉愚蠢的复制 - 粘贴:)

标签: javascript function this dom-events colorbox


【解决方案1】:

onOpen: p.showPopup($(this).attr('type)) 的问题在于它会在你将它绑定到 onOpen 的那一刻运行 p.showPopup 函数。您想要的是它在触发 onOpen 事件时运行。使用

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

改为

(编辑)假设 p.showPopup 已定义,我在您的代码中看不到它。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-11-16
    • 2021-11-12
    • 1970-01-01
    相关资源
    最近更新 更多