我正在使用 JQuery Boilerplate 编写我的第一个 JQuery 插件 - 响应式轮播。我正在使用另一个插件(SSM - http://www.simplestatemanager.com/)为每个设备 View 创建状态。因此,在移动设备上,functionA 将运行,在平板电脑上,functionB 和桌面上的 functionC 等将运行。
对于 SSM 创建的每个状态,都可以添加相应的 onEnter 回调函数,并且我添加了 3 个合适的函数以在发生这种情况时运行。正如您从下面的代码中看到的,onEnterDesktop 函数在桌面设备上运行。然后,我尝试从这个名为 createCarousel() 的函数中运行进一步的函数,但收到错误“createCarousel 未定义”。
我相信这是由于范围问题造成的,浏览器无法从 onEnterDesktop 函数中找到 createCarousel。我该如何解决这个问题?
任何帮助都会很棒。这是我的插件的代码:
;(function ( $, window, document, undefined ) {
// Create the defaults once
var pluginName = "dcResponsiveCarousel",
defaults = {
propertyName: "value"
};
function Plugin( element, options ) {
this.element = element;
this.$element = $(element);
this.options = $.extend( {}, defaults, options) ;
this._defaults = defaults;
this._name = pluginName;
this.init();
}
Plugin.prototype = {
init: function() {
ssm.addStates([
{
id: 'mobile',
maxWidth: 767,
onEnter: this.onEnterMobile
},
{
id: 'tablet',
maxWidth: 991,
minWidth: 768,
onEnter: this.onEnterTablet
},
{
id: 'desktop',
minWidth: 992,
onEnter: this.onEnterDesktop
}
]);
ssm.ready();
},
onEnterMobile: function (){
console.log("You've entered mobile screen dimension territory");
var itemsPerPage = 1;
console.log(itemsPerPage);
},
onEnterTablet: function (){
console.log("You've entered tablet screen dimension territory");
var itemsPerPage = 2;
console.log(itemsPerPage);
},
onEnterDesktop: function (){
console.log("You've entered desktop screen dimension territory");
var itemsPerPage = 3;
createCarousel();
},
createCarousel: function (){
var $carouselItems = this.$element.children(".item"),
$carouselItemsLength = $carouselItems.length,
$carouselItemsWidth = 0;
for (var i = 0; i < $carouselItemsLength; i++) {
$carouselItemsWidth = $carouselItemsWidth + $carouselItems.eq(i).outerWidth();
};
console.log($carouselItemsWidth);
this.$element
}
};
$.fn[pluginName] = function ( options ) {
return this.each(function () {
if (!$.data(this, "plugin_" + pluginName)) {
$.data(this, "plugin_" + pluginName,
new Plugin( this, options ));
}
});
};
})( jQuery, window, document );
最佳答案
它是一个对象文字,因此 createCarousel
未定义,Plugin.prototype.createCarousel
是,或者在您所在的范围内,this.createCarousel() ;
onEnterDesktop: function (){
console.log("You've entered desktop screen dimension territory");
var itemsPerPage = 3;
Plugin.prototype.createCarousel();
},
关于使用 JQuery Boilerplate 的 Javascript 范围问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20824364/