【发布时间】:2017-05-02 11:48:22
【问题描述】:
我正在编写一个 jQuery 插件,它加载一个小部件(GET 方法),稍后应该触发一个点击事件。
初始化插件时元素选择器不在 DOM 中。那么如何实现选择器的全局存储来处理点击事件呢?
我使代码简短易懂。
(function($) {
var $template; // the global variable
$.fn.myPlugin = function() {
$(this).bind('click', function(e) {
$.get('/template.html', function(data) {
$('body').append(data);
$template = $(data); // set global variable here
}
}
// fire click event on global variable here, but $template is undefined
$(document).on('click', $template.find('.button'), function() {
// do something
}
}
})(jQuery);
谢谢!
【问题讨论】:
标签: jquery plugins jquery-plugins scope global-variables